Skip to main content

hooks/use-local-storage

Functions​

useLocalStorage()​

useLocalStorage<T>(key, initialValue, isValid?): [T, (value) => void, () => void]

Defined in: hooks/use-local-storage.ts:29

State persisted to localStorage as JSON. The first render uses initialValue and storage is read after mount, so it matches the server render.

isValid guards the stored value: when it returns false (stale schema, hand-edited entry) the stored value is ignored and initialValue is kept. Without it, a stored value is kept only if its typeof (and array-ness) matches initialValue, which rejects the raw string getLocalStorage returns for an entry that isn't valid JSON. The check is skipped when initialValue is null or undefined; for union types, pass isValid.

The third tuple item removes the entry and resets to initialValue.

Type Parameters​

T​

T

Parameters​

key​

string

initialValue​

T

isValid?​

(value) => value is T

Returns​

[T, (value) => void, () => void]