← Back to React, page 8

react-0146 · Hard senior

How do you persist state in localStorage correctly, including cross-tab sync and server rendering?

Treat localStorage as an external store and read it with useSyncExternalStore. Subscribe to the window storage event so other tabs update this one, provide a server snapshot so server and first client renders match, and wrap storage access in try/catch for private mode and quota errors. Do not read localStorage during the first render in an SSR app with useState, because it causes hydration mismatches. The storage event does not fire in the tab that made the change, so notify local listeners yourself.

Full answer

Naive persistence reads localStorage in a useState initializer and writes in an effect. It works in a single tab on the client, but breaks in common cases.

Problems:

  • Other tabs. A change in tab A leaves tab B showing old data until reload. The storage event fires in other tabs of the same origin (not the tab that wrote), so you can subscribe to it.
  • Server rendering. There is no localStorage on the server. If the client's first render uses the stored value, its HTML differs from the server HTML, which causes a hydration mismatch.
  • Failures. Access can throw in private modes, when storage is blocked or full, and stored values can be corrupted JSON.

Solution: useSyncExternalStore. Pass subscribe (adds a storage listener and a listener for local changes), getSnapshot (reads the current string from storage) and getServerSnapshot (returns a default). During hydration React uses the server snapshot, then re-renders with the real value if different, without a mismatch error. Writes go through a function that sets storage and notifies local subscribers, because the browser does not send the event to the writing tab.

Details:

  • Snapshots must be stable: return primitives (strings) from getSnapshot and parse outside, or cache the parsed value, otherwise React loops.
  • Validate and version stored data, and fall back to a default for bad JSON.
  • Store small, non-sensitive values only. Never store secrets or tokens that need protection.
  • For richer needs use libraries (Zustand persist, redux-persist), IndexedDB for large data, and BroadcastChannel for messages between tabs.

The example is a theme hook that follows other tabs.

jsx
import { useSyncExternalStore } from 'react';

const listeners = new Set();

function subscribe(listener) {
  listeners.add(listener);
  window.addEventListener('storage', listener);
  return () => {
    listeners.delete(listener);
    window.removeEventListener('storage', listener);
  };
}

function readTheme() {
  try {
    return window.localStorage.getItem('theme') ?? 'light';
  } catch {
    return 'light';
  }
}

function writeTheme(value) {
  try {
    window.localStorage.setItem('theme', value);
  } catch {
    // Storage may be blocked or full. Keep the app working.
  }
  listeners.forEach((listener) => listener());
}

export default function ThemeSwitcher() {
  const theme = useSyncExternalStore(subscribe, readTheme, () => 'light');
  return (
    <div>
      <p>Theme: {theme}</p>
      <button onClick={() => writeTheme('dark')}>Set dark</button>
    </div>
  );
}

The check set the theme in this tab and then simulated a write from another tab, by changing storage and dispatching a storage event. The component followed both changes. Output of the run: start: Theme: light | stored: null after Set dark in this tab: Theme: dark | stored: dark after another tab changed it: Theme: light | stored: light

Key points

  • Read localStorage through useSyncExternalStore and not through a useState initializer.
  • The storage event reaches other tabs only, so notify local subscribers on writes.
  • Supply getServerSnapshot to avoid hydration mismatches.
  • Wrap access in try/catch and return stable snapshot values.
  • Keep stored data small, validated and non-sensitive.

Common mistakes

  • Reading localStorage in a useState initializer in a server-rendered app.
  • Expecting the storage event to fire in the same tab.
  • Parsing JSON inside getSnapshot and returning a new object each time.
  • Not handling blocked storage or invalid data.
  • Storing tokens or private data in localStorage.

Follow-ups

  • Why does useSyncExternalStore need getServerSnapshot?
  • When would you choose BroadcastChannel or IndexedDB?
  • How do you migrate the format of persisted data between versions?

Tips

  • Mention three failure modes: other tabs, SSR and storage errors.
  • Say that the writing tab does not receive the storage event.
  • Mention stable snapshots.