From 65e903582f2064ce373e51565021bffcca6b63ca Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 10 Oct 2022 08:57:36 -0400 Subject: [PATCH] memo --- app/hooks/useLastVisitedPath.tsx | 10 +++++++--- app/hooks/usePersistedState.ts | 29 ++++++++++++++++------------- 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/app/hooks/useLastVisitedPath.tsx b/app/hooks/useLastVisitedPath.tsx index 8564cea3e..9d57b8807 100644 --- a/app/hooks/useLastVisitedPath.tsx +++ b/app/hooks/useLastVisitedPath.tsx @@ -1,3 +1,4 @@ +import * as React from "react"; import usePersistedState from "~/hooks/usePersistedState"; export default function useLastVisitedPath() { @@ -6,9 +7,12 @@ export default function useLastVisitedPath() { "/" ); - const setPathAsLastVisitedPath = (path: string) => { - path !== lastVisitedPath && setLastVisitedPath(path); - }; + const setPathAsLastVisitedPath = React.useCallback( + (path: string) => { + path !== lastVisitedPath && setLastVisitedPath(path); + }, + [lastVisitedPath, setLastVisitedPath] + ); return [lastVisitedPath, setPathAsLastVisitedPath]; } diff --git a/app/hooks/usePersistedState.ts b/app/hooks/usePersistedState.ts index 8619e2bef..f6edbbda1 100644 --- a/app/hooks/usePersistedState.ts +++ b/app/hooks/usePersistedState.ts @@ -15,7 +15,7 @@ import useEventListener from "./useEventListener"; export default function usePersistedState( key: string, defaultValue: Primitive -) { +): [Primitive, (value: Primitive) => void] { const [storedValue, setStoredValue] = React.useState(() => { if (typeof window === "undefined") { return defaultValue; @@ -23,19 +23,22 @@ export default function usePersistedState( return Storage.get(key) ?? defaultValue; }); - const setValue = (value: Primitive | ((value: Primitive) => void)) => { - try { - // Allow value to be a function so we have same API as useState - const valueToStore = - value instanceof Function ? value(storedValue) : value; + const setValue = React.useCallback( + (value: Primitive | ((value: Primitive) => void)) => { + try { + // Allow value to be a function so we have same API as useState + const valueToStore = + value instanceof Function ? value(storedValue) : value; - setStoredValue(valueToStore); - Storage.set(key, valueToStore); - } catch (error) { - // A more advanced implementation would handle the error case - Logger.debug("misc", "Failed to persist state", { error }); - } - }; + setStoredValue(valueToStore); + Storage.set(key, valueToStore); + } catch (error) { + // A more advanced implementation would handle the error case + Logger.debug("misc", "Failed to persist state", { error }); + } + }, + [key, storedValue] + ); // Listen to the key changing in other tabs so we can keep UI in sync useEventListener("storage", (event: StorageEvent) => {