Skip to content

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 undefined removes the key from localStorage

Behavior

  • SSR-safe: no access to window on the server
  • Serialization: values are stored via JSON.stringify
  • Synchronization: listens for window storage events and updates when the same key changes 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>
);
}