@goodnight-dev/react-hooks
    Preparing search index...

    Function useLocalStorage

    • 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.

      • initialValue: T

        Returned when key has nothing stored yet, and used as-is during SSR (there is no localStorage on the server).

      Returns [T, (value: SetValue<T>) => void]

      const [settings, setSettings] = useLocalStorage(`users-${userId}`, defaultSettings);
      setSettings((previous) => ({ ...previous, theme: 'dark' }));