useLocalStorage
React hook to persist state in localStorage with cross-tab synchronization, custom serializers, and reactive callbacks.
Demo
localStorage["demo:note"]
Usage
Shorthand — key + optional callback:
Full props object:
Parameters
Shorthand form
| Parameter | Type | Description |
|---|---|---|
key | string | The localStorage key. |
onChange | (value: T | null) => void | Optional. Called on every value change, including cross-tab syncs. |
Object form
| Property | Type | Default | Description |
|---|---|---|---|
key | string | — | The localStorage key. |
defaultValue | T | null | Value returned when the key does not exist. |
serializer | Serializer<T> | JSON.parse / JSON.stringify | Custom serializer for non-JSON values. |
onChange | (value: T | null) => void | — | Called on every value change, including cross-tab syncs. |
onRemove | () => void | — | Called when the key is removed via remove() or localStorage.clear(). |
Return Values
Returns a tuple [value, set, remove]:
| Index | Type | Description |
|---|---|---|
value | T | null | Current value. null when the key is absent and no defaultValue is set. |
set | (value: T) => void | Writes to localStorage, updates state, fires onChange. |
remove | () => void | Deletes the key, resets to defaultValue, fires onRemove and onChange(null). |
Custom Serializer
Cross-tab Sync
onChange fires in every tab that shares the same key. No extra setup needed — the hook listens to the native window storage event internally.