ReactMedium

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

  1. Same API as useState: [value, setValue], where setValue accepts a value or an updater function.
  2. Lazy read on mount, with initialValue as the fallback.
  3. JSON serialization with try/catch (storage can be full, disabled or contain corrupt data).
  4. Cross-tab sync: the browser fires a storage event in other tabs.
  5. Same-tab sync: components using the same key on one page should update together; dispatch a custom event when writing.
  6. SSR: localStorage does not exist on the server; return initialValue from the server snapshot to avoid hydration mismatches.
  7. 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

  • localStorage is 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

tsx
1import { useCallback, useMemo, useSyncExternalStore } from "react";
2
3const EVENT = "local-storage";
4
5function subscribe(callback: () => void) {
6 window.addEventListener("storage", callback); // other tabs
7 window.addEventListener(EVENT, callback); // same tab
8 return () => {
9 window.removeEventListener("storage", callback);
10 window.removeEventListener(EVENT, callback);
11 };
12}
13
14export function useLocalStorage<T>(key: string, initialValue: T) {
15 const raw = useSyncExternalStore(
16 subscribe,
17 () => { try { return localStorage.getItem(key); } catch { return null; } }, // string: stable snapshot
18 () => null // server snapshot
19 );
20
21 const value = useMemo<T>(() => {
22 if (raw === null) return initialValue;
23 try { return JSON.parse(raw) as T; } catch { return initialValue; }
24 }, [raw, initialValue]);
25
26 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 disabled
33 }
34 window.dispatchEvent(new Event(EVENT)); // notify other hooks on this page
35 },
36 [key, value]
37 );
38
39 const remove = useCallback(() => { localStorage.removeItem(key); window.dispatchEvent(new Event(EVENT)); }, [key]);
40 return [value, setValue, remove] as const;
41}
42
43// 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.

Open in study app