ESC

Type to search the knowledge base.

External Store Subscriptions

Subscribe to non-React stores without tearing: the problem with useEffect + useState, and useSyncExternalStore.

advanced3 min read
  • react
  • external-store

Many apps read data from stores outside React: Redux, Zustand, browser APIs (window.matchMedia), or legacy globals. Naively wiring them with useEffect + useState can tear under concurrent rendering — UI shows inconsistent snapshots mid-update.

Docs: useSyncExternalStore.

The naive pattern (problematic)

function useStore(store) {
  const [value, setValue] = useState(() => store.get());
  useEffect(() => store.subscribe(() => setValue(store.get())), [store]);
  return value;
}

Concurrent features may render with a store value that changes before commit, producing mismatched UI branches.

The correct primitive

import { useSyncExternalStore } from 'react';

function useStore(store) {
  return useSyncExternalStore(
    store.subscribe,
    store.getSnapshot,
    store.getServerSnapshot // optional SSR
  );
}

getSnapshot must return an immutable snapshot; if data is equal, return the same reference to avoid infinite re-renders.

const store = {
  state: { n: 0 },
  listeners: new Set(),
  subscribe(listener) {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  },
  getSnapshot() {
    return this.state;
  },
  set(partial) {
    this.state = { ...this.state, ...partial };
    this.listeners.forEach((l) => l());
  },
};

SSR

Provide getServerSnapshot so server render and hydration agree — otherwise you fight hydration mismatches.

When libraries handle it

Redux Toolkit, Zustand, and others already use useSyncExternalStore under the hood. Prefer their hooks instead of hand-rolling.

Interview out-loud

“External stores need useSyncExternalStore so React can read a consistent snapshot and subscribe without tearing under concurrent render. getSnapshot should be pure and referentially stable when data is unchanged. I use library hooks when available.”

Further reading

Edge cases worth rehearsing

Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.

Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.

When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.

Edge cases worth rehearsing

Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.

Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.

When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.

Related guides