useSyncExternalStore and external subscriptions
useSyncExternalStore is React's built-in Hook for reading from a source that lives outside React and can notify subscribers when that source changes.
const snapshot = useSyncExternalStore(
subscribe,
getSnapshot,
getServerSnapshot,
);
It solves a different problem from Context.
What counts as an external store?β
Examples include custom JavaScript stores, browser subscription APIs, third-party state libraries, state shared with non-React code, and any source with snapshot + subscription semantics.
βExternalβ describes ownershipβnot necessarily global scope.
Basic mental modelβ
React needs two capabilities:
When the store notifies React, React reads the snapshot again and decides whether the rendered value changed.
Minimal external storeβ
let todos = [];
const listeners = new Set();
export const todosStore = {
getSnapshot() {
return todos;
},
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
addTodo(todo) {
todos = [...todos, todo];
for (const listener of listeners) listener();
},
};
React consumer:
function TodoList() {
const todos = useSyncExternalStore(
todosStore.subscribe,
todosStore.getSnapshot,
);
return todos.map(todo => <p key={todo.id}>{todo.text}</p>);
}
Subscription lifecycleβ
subscribe should register the callback and return a cleanup function that removes it.
Snapshot identity is part of the contractβ
If the store has not changed, repeated getSnapshot() calls should return an Object.is-equal value.
Bad:
function getSnapshot() {
return [...todos]; // β new identity every call
}
Better:
function getSnapshot() {
return todos;
}
Create a new immutable snapshot only when the store actually changes.
If the underlying source mutates in place, cache an immutable snapshot and replace that cache only when relevant data changes.
Browser API example: online statusβ
function subscribe(callback) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
function getSnapshot() {
return navigator.onLine;
}
export function useOnlineStatus() {
return useSyncExternalStore(subscribe, getSnapshot);
}
This is a natural fit because the browser owns the authoritative value.
Why not useEffect + useState?β
A manual subscription can work for simple sources, but useSyncExternalStore exists specifically to integrate externally owned mutable state with React's rendering model and concurrency expectations.
If you are building or adapting an external store, prefer the dedicated primitive.
Hide mechanics behind a custom Hookβ
export function useTodos() {
return useSyncExternalStore(
todosStore.subscribe,
todosStore.getSnapshot,
);
}
Consumers should depend on a domain API rather than repeat subscription plumbing.
subscribe identity mattersβ
Defining a new subscribe function during every render can cause unnecessary resubscription.
function Component() {
const value = useSyncExternalStore(
callback => store.subscribe(callback),
store.getSnapshot,
);
}
Prefer a stable subscription function outside the component when possible, or use a library abstraction that owns this efficiently.
Parameterized subscriptionsβ
A store may subscribe by identifier:
function useProject(projectId) {
return useSyncExternalStore(
callback => projectStore.subscribe(projectId, callback),
() => projectStore.getSnapshot(projectId),
);
}
This can be valid, but function identity, snapshot caching, and selector design become part of the store architecture.
getServerSnapshotβ
The optional third argument supports server rendering and hydration.
const value = useSyncExternalStore(
subscribe,
getSnapshot,
getServerSnapshot,
);
getServerSnapshot returns the value used during server rendering and the initial hydration path.
For browser-only data such as online status, the server may choose a deterministic placeholder snapshot:
function getServerSnapshot() {
return true;
}
Hydration consistencyβ
The exact transfer mechanism is framework/application specific. The important contract is that server and initial client snapshots agree enough for hydration.
βThe result of getSnapshot should be cachedββ
A common cause is returning a new object on every read:
function getSnapshot() {
return {count: store.count}; // β
}
Instead, update a cached snapshot only when state changes:
let snapshot = {count: 0};
function increment() {
snapshot = {count: snapshot.count + 1};
emitChange();
}
function getSnapshot() {
return snapshot;
}
External stores and selectorsβ
Reading one property from a whole-store snapshot does not automatically create a fine-grained subscription.
const state = useSyncExternalStore(store.subscribe, store.getSnapshot);
const total = state.cart.total;
The subscription still observes the snapshot returned by getSnapshot. Fine-grained selector behaviour requires store/library design that supports the desired comparison/subscription semantics.
Context + external storeβ
Context and external stores can work together.
<StoreContext value={workspaceStore}>
<Workspace />
</StoreContext>
function useWorkspaceSnapshot() {
const store = useContext(StoreContext);
return useSyncExternalStore(
store.subscribe,
store.getSnapshot,
store.getServerSnapshot,
);
}
This allows store A and store B to exist in separate provider subtrees without requiring one global singleton.
When to use this Hook directlyβ
Use it directly when building your own external-store abstraction, integrating browser subscription APIs, connecting mutable state outside React, or authoring React bindings for a library.
Application code using Redux, Zustand, or similar libraries normally uses the library's own React Hooks rather than wiring useSyncExternalStore manually.
Not a replacement for local stateβ
Not a server-state cacheβ
useSyncExternalStore does not automatically provide fetching, caching policy, invalidation, deduplication, retries, mutations, or pagination. It synchronizes React with an external source; it does not define that source's domain lifecycle.
Concurrency mental modelβ
React can reason about the source only through the snapshot contract you provide.
Do not mutate a snapshot behind React's back while continuing to return the same identity.
Exerciseβ
Build a preferences store containing compactMode and fontScale. Make snapshots immutable/stable, implement subscribe/unsubscribe, expose a usePreferencesStore Hook, and explain how this differs from Context + useReducer.
Interview questionsβ
Mid-level: What problem does useSyncExternalStore solve?
Senior: Why must an unchanged store return a stable snapshot identity?
Staff: How would you design SSR/hydration for an external store, and how would you scope multiple store instances safely?
Summaryβ
Referencesβ
Nextβ
Continue into the state-management ecosystem chapters, where Context, Redux Toolkit, Zustand, TanStack Query, React Hook Form, and URL state are compared by ownership and lifecycle.