diff --git a/src/useLocalStorage.ts b/src/useLocalStorage.ts index 0415f06090..7e6a3a64c1 100644 --- a/src/useLocalStorage.ts +++ b/src/useLocalStorage.ts @@ -5,21 +5,22 @@ type Dispatch = (value: A) => void; type SetStateAction = S | ((prevState: S) => S); const noop = () => {}; +const isUndefined = (value?: any): boolean => typeof value === 'undefined'; const useLocalStorage = ( key: string, initialValue?: T, raw?: boolean -): [T | null, Dispatch>, () => void] => { +): [T | undefined, Dispatch>, () => void] => { if (!isClient) { return [initialValue as T, noop, noop]; } - const [state, setState] = useState(() => { + const [state, setState] = useState(() => { try { const localStorageValue = localStorage.getItem(key); - if (typeof initialValue === 'undefined' && typeof localStorageValue !== 'string') { - return null; + if (isUndefined(initialValue)) { + return undefined; } if (typeof localStorageValue !== 'string') { localStorage.setItem(key, raw ? String(initialValue) : JSON.stringify(initialValue)); @@ -37,7 +38,7 @@ const useLocalStorage = ( const remove = useCallback(() => { try { localStorage.removeItem(key); - setState(null); + setState(undefined); } catch { // If user is in private mode or has storage restriction // localStorage can throw. @@ -45,7 +46,7 @@ const useLocalStorage = ( }, [key, setState]); useEffect(() => { - if (state === null) return; + if (isUndefined(state)) return; try { const serializedState = raw ? String(state) : JSON.stringify(state); localStorage.setItem(key, serializedState);