Read and write a JSON-serializable value in localStorage, keyed by
key, re-rendering on change — including changes made from another tab.
Mirrors useState's own [value, setValue] shape rather than a
mutate-in-place object, so there is exactly one write path to reason
about. Backed by useSyncExternalStore: localStorage is the single
source of truth (nothing is cached in React state), so getSnapshot
re-reads it on every call, and setValue's functional-update form always
sees the current stored value, not a stale render's closure.
initialValue is only ever used the first time a key has nothing stored
for it, and — same as useState — only its first value is honored;
passing a new literal on a later render does not overwrite what is
already stored, so memoize non-primitive defaults yourself if you want to
avoid recreating them every render.
Type Parameters
T
Parameters
key: string
The localStorage key. Changing it switches to that key's
own value, subscribing and reading independently.
Read and write a JSON-serializable value in
localStorage, keyed bykey, re-rendering on change — including changes made from another tab.Mirrors
useState's own[value, setValue]shape rather than a mutate-in-place object, so there is exactly one write path to reason about. Backed byuseSyncExternalStore:localStorageis the single source of truth (nothing is cached in React state), sogetSnapshotre-reads it on every call, andsetValue's functional-update form always sees the current stored value, not a stale render's closure.initialValueis only ever used the first time a key has nothing stored for it, and — same asuseState— only its first value is honored; passing a new literal on a later render does not overwrite what is already stored, so memoize non-primitive defaults yourself if you want to avoid recreating them every render.