useSyncExternalStore Overview
useSyncExternalStore API deep dive: subscribe, getSnapshot, server snapshot, and mutation rules.
- 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
subscribe(callback)— registercallbackto run when the store mutates; return unsubscribe.getSnapshot()— pure read of current store data used during render.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.”
Related on this site
- External Store Subscriptions
- Concurrent Features Overview
- Context Performance Pitfalls
- Hydration Mismatches
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
- Accessibility Patterns in ReactPractical React a11y: labels, focus management, keyboard, live regions, and composition patterns that stay accessible.
- Avoid Prop Drilling with CompositionStop threading props through intermediates: children slots, inversion of control, and when context is the right escape hatch.
- Batching State UpdatesHow React 18+ batches setState in events, timeouts, and promises: when updates flush and why double setState still works.
- Children Prop PatternsUsing children and slot props for flexible APIs: wrappers, compound components, and when to prefer explicit props.
- Client Component BoundariesWhere to put use client: push interactivity to leaves, serializable props, and children as server slots.