Persist state in localStorage with React. Syncs across tabs and survives refresh.
import { useState, useEffect } from 'react';
export function useLocalStorage<T>(key: string, initialValue: T): [T, (v: T | ((prev: T) => T)) => void] {
const [value, setValue] = useState<T>(() => {
if (typeof window === 'undefined') return initialValue;
try {
const item = window.localStorage.getItem(key);
return item != null ? JSON.parse(item) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch (e) {
console.warn('localStorage set failed', e);
}
}, [key, value]);
return [value, setValue];
}Paste it into your hooks folder or next to the component.
Call useLocalStorage('theme', 'dark') to get [value, setValue]. Updates persist across refreshes and tabs.
const [theme, setTheme] = useLocalStorage('theme', 'dark');