Build a useLocalStorage hook with sync across tabs
Write a useLocalStorage hook for React 19 on top of useSyncExternalStore so values stay in sync between components and across browser tabs via storage events.
useState plus localStorage drifts when another tab writes. useSyncExternalStore subscribes to the external source properly and avoids hydration mismatches.
import { useCallback, useSyncExternalStore } from 'react';
export function useLocalStorage(key, initial) {
const subscribe = useCallback((cb) => {
window.addEventListener('storage', cb);
window.addEventListener(`local:${key}`, cb);
return () => {
window.removeEventListener('storage', cb);
window.removeEventListener(`local:${key}`, cb);
};
}, [key]);
const raw = useSyncExternalStore(
subscribe,
() => localStorage.getItem(key),
() => null,
);
const value = raw === null ? initial : JSON.parse(raw);
const set = (next) => {
localStorage.setItem(key, JSON.stringify(next));
window.dispatchEvent(new Event(`local:${key}`));
};
return [value, set];
}Tab A: set("dark") -> Tab A and Tab B both re-render with "dark"The storage event fires only in other tabs, so the hook dispatches its own event for same-tab listeners. The third argument gives the server snapshot, which prevents a hydration mismatch. See [useSyncExternalStore](https://react.dev/reference/react/useSyncExternalStore).
getSnapshot must return a stable primitive, which is why the raw string is read and parsed afterwards.
Wrap the JSON.parse in a try/catch if other code might write invalid text to the same key, otherwise a bad value will crash the render.