useLocalStorage
useLocalStorage
A simple React hook to read/write values from localStorage and keep them in sync across tabs via the native storage event.
API
const [value, setValue] = useLocalStorage(key, defaultValue);- key: string key to store under
- defaultValue: value used when key is missing or during SSR
- value: current value (parsed from JSON; falls back to raw string if not JSON)
- setValue: updates the value; accepts a value or an updater function
- Passing
undefinedremoves the key fromlocalStorage
- Passing
Behavior
- SSR-safe: no access to
windowon the server - Serialization: values are stored via
JSON.stringify - Synchronization: listens for
windowstorageevents and updates when the samekeychanges in another tab/window
Example
import useLocalStorage from '@power-rent/hooks/useLocalStorage';
function Example() { const [theme, setTheme] = useLocalStorage('theme', 'light');
return ( <button onClick={() => setTheme((t) => (t === 'light' ? 'dark' : 'light'))}> Toggle theme (current: {theme}) </button> );}