From 67caa0db0f7f097c22f9cbee55c23575f12c2801 Mon Sep 17 00:00:00 2001 From: Alasdair North Date: Wed, 15 May 2024 11:16:45 +0100 Subject: [PATCH] Add useMemo call to useLocalStorage so that the value returned only changes if store actually changes. --- index.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index f6e4fe2..4e645ea 100644 --- a/index.js +++ b/index.js @@ -622,10 +622,14 @@ export function useLocalStorage(key, initialValue) { getLocalStorageServerSnapshot ); + const currentValue = React.useMemo(() => { + return store ? JSON.parse(store) : initialValue; + }, [store, initialValue]); + const setState = React.useCallback( (v) => { try { - const nextState = typeof v === "function" ? v(JSON.parse(store)) : v; + const nextState = typeof v === "function" ? v(currentValue) : v; if (nextState === undefined || nextState === null) { removeLocalStorageItem(key); @@ -636,7 +640,7 @@ export function useLocalStorage(key, initialValue) { console.warn(e); } }, - [key, store] + [key, currentValue] ); React.useEffect(() => { @@ -648,7 +652,7 @@ export function useLocalStorage(key, initialValue) { } }, [key, initialValue]); - return [store ? JSON.parse(store) : initialValue, setState]; + return [currentValue, setState]; } export function useLockBodyScroll() {