Sync component state with localStorage.
Section: Common UI Hooks
Persist state to localStorage
tsx
tsx
function useLocalStorage<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(() => {
const raw = localStorage.getItem(key);
return raw ? JSON.parse(raw) as T : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue] as const;
}Explanation
A classic custom hook for persistence; remember browser-only constraints if server rendering is involved.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Common UI Hooks
Handle clicks outside an element
Close menus or popovers when a click happens outside a ref.
Custom hook with options object
Prefer options objects for extensible APIs.