diff --git a/index.js b/index.js index f6e4fe2..8917fa2 100644 --- a/index.js +++ b/index.js @@ -639,16 +639,22 @@ export function useLocalStorage(key, initialValue) { [key, store] ); + const initialValueRef = React.useRef(initialValue); + React.useEffect(() => { if ( getLocalStorageItem(key) === null && - typeof initialValue !== "undefined" + typeof initialValueRef.current !== "undefined" ) { - setLocalStorageItem(key, initialValue); + setLocalStorageItem(key, initialValueRef.current); } - }, [key, initialValue]); + }, [key]); + + const result = React.useMemo(() => { + return store ? JSON.parse(store) : initialValueRef.current; + }, [store]); - return [store ? JSON.parse(store) : initialValue, setState]; + return [result, setState]; } export function useLockBodyScroll() { @@ -1200,16 +1206,22 @@ export function useSessionStorage(key, initialValue) { [key, store] ); + const initialValueRef = React.useRef(initialValue); + React.useEffect(() => { if ( getSessionStorageItem(key) === null && - typeof initialValue !== "undefined" + typeof initialValueRef.current !== "undefined" ) { - setSessionStorageItem(key, initialValue); + setSessionStorageItem(key, initialValueRef.current); } - }, [key, initialValue]); + }, [key]); + + const result = React.useMemo(() => { + return store ? JSON.parse(store) : initialValueRef.current; + }, [store]); - return [store ? JSON.parse(store) : initialValue, setState]; + return [result, setState]; } export function useSet(values) {