Skip to content
jshacks.dev
Frameworks

Build a useLocalStorage hook with sync across tabs

Write a useLocalStorage hook for React 19 on top of useSyncExternalStore so values stay in sync between components and across browser tabs via storage events.

1 min read
Summarize in AI

useState plus localStorage drifts when another tab writes. useSyncExternalStore subscribes to the external source properly and avoids hydration mismatches.

JSX
import { useCallback, useSyncExternalStore } from 'react';

export function useLocalStorage(key, initial) {
  const subscribe = useCallback((cb) => {
    window.addEventListener('storage', cb);
    window.addEventListener(`local:${key}`, cb);
    return () => {
      window.removeEventListener('storage', cb);
      window.removeEventListener(`local:${key}`, cb);
    };
  }, [key]);

  const raw = useSyncExternalStore(
    subscribe,
    () => localStorage.getItem(key),
    () => null,
  );

  const value = raw === null ? initial : JSON.parse(raw);

  const set = (next) => {
    localStorage.setItem(key, JSON.stringify(next));
    window.dispatchEvent(new Event(`local:${key}`));
  };

  return [value, set];
}
Text
Tab A: set("dark")  ->  Tab A and Tab B both re-render with "dark"

The storage event fires only in other tabs, so the hook dispatches its own event for same-tab listeners. The third argument gives the server snapshot, which prevents a hydration mismatch. See [useSyncExternalStore](https://react.dev/reference/react/useSyncExternalStore).

getSnapshot must return a stable primitive, which is why the raw string is read and parsed afterwards.

Wrap the JSON.parse in a try/catch if other code might write invalid text to the same key, otherwise a bad value will crash the render.

Taggedreact 19
Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.