ESC

Type to search the knowledge base.

useSyncExternalStore Overview

useSyncExternalStore API deep dive: subscribe, getSnapshot, server snapshot, and mutation rules.

advanced3 min read
  • react
  • usesyncexternalstore-overview

useSyncExternalStore is the supported way to subscribe a component to an external mutable source so concurrent rendering stays correct.

const state = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?);

Docs: useSyncExternalStore.

Contract

  1. subscribe(callback) — register callback to run when the store mutates; return unsubscribe.
  2. getSnapshot() — pure read of current store data used during render.
  3. getServerSnapshot() — snapshot for SSR; must match initial client hydration when possible.

If getSnapshot returns a new object every call even when data is equal, React re-renders endlessly. Cache the snapshot on the store until mutation:

let snapshot = { width: 0 };
function getSnapshot() {
  return snapshot;
}
function onResize() {
  snapshot = { width: window.innerWidth };
  listeners.forEach((l) => l());
}

Browser API example

function useMediaQuery(query) {
  return useSyncExternalStore(
    (onChange) => {
      const mql = window.matchMedia(query);
      mql.addEventListener('change', onChange);
      return () => mql.removeEventListener('change', onChange);
    },
    () => window.matchMedia(query).matches,
    () => false // server assumption
  );
}

Do not mutate during render

Snapshots are read during render. Mutations belong in event handlers or store updaters that notify listeners after the new snapshot is in place.

Versus context

Context is React-owned state propagated down the tree. External stores live outside and push notifications. High-frequency external data often fits stores better than context (context pitfalls).

Interview out-loud

“useSyncExternalStore takes subscribe and getSnapshot so React integrates external data safely. Snapshots must be immutable and stable when unchanged. For SSR I provide getServerSnapshot. Most state libraries already wrap this API.”

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