useLocalStorage hook
useLocalStorage(key, initialValue) behaves like useState but persists the value in localStorage. It reads the stored value lazily on first render, writes on every change, handles invalid JSON and unavailable storage, supports updater functions, and stays in sync across tabs and across components on the same page. Building it on useSyncExternalStore makes it concurrency-safe and SSR-friendly.
Requirements
- Same API as
useState:[value, setValue], wheresetValueaccepts a value or an updater function. - Lazy read on mount, with
initialValueas the fallback. - JSON serialization with
try/catch(storage can be full, disabled or contain corrupt data). - Cross-tab sync: the browser fires a
storageevent in other tabs. - Same-tab sync: components using the same key on one page should update together; dispatch a custom event when writing.
- SSR:
localStoragedoes not exist on the server; returninitialValuefrom the server snapshot to avoid hydration mismatches. - Optional
remove().
Why useSyncExternalStore
localStorage is an external store. useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) subscribes to changes and avoids tearing. getSnapshot must return a stable value for unchanged data, so return the raw string and parse it with useMemo.
Caveats
localStorageis synchronous and limited (about 5MB); do not store large data or secrets (any script can read it).- For large or structured data, use IndexedDB (via
idb-keyval, Dexie).
Code example
1import { useCallback, useMemo, useSyncExternalStore } from "react";23const EVENT = "local-storage";45function subscribe(callback: () => void) {6 window.addEventListener("storage", callback); // other tabs7 window.addEventListener(EVENT, callback); // same tab8 return () => {9 window.removeEventListener("storage", callback);10 window.removeEventListener(EVENT, callback);11 };12}1314export function useLocalStorage<T>(key: string, initialValue: T) {15 const raw = useSyncExternalStore(16 subscribe,17 () => { try { return localStorage.getItem(key); } catch { return null; } }, // string: stable snapshot18 () => null // server snapshot19 );2021 const value = useMemo<T>(() => {22 if (raw === null) return initialValue;23 try { return JSON.parse(raw) as T; } catch { return initialValue; }24 }, [raw, initialValue]);2526 const setValue = useCallback(27 (next: T | ((prev: T) => T)) => {28 const resolved = typeof next === "function" ? (next as (p: T) => T)(value) : next;29 try {30 localStorage.setItem(key, JSON.stringify(resolved));31 } catch (e) {32 console.warn("localStorage write failed", e); // quota exceeded or disabled33 }34 window.dispatchEvent(new Event(EVENT)); // notify other hooks on this page35 },36 [key, value]37 );3839 const remove = useCallback(() => { localStorage.removeItem(key); window.dispatchEvent(new Event(EVENT)); }, [key]);40 return [value, setValue, remove] as const;41}4243// const [cart, setCart] = useLocalStorage<string[]>("cart", []);44// setCart((c) => [...c, "pen"]);
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.