Skip to main content

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.

Context vs useSyncExternalStore
Context
Distributes a React-tree value from the nearest provider.
useSyncExternalStore
Subscribes React rendering to an externally owned mutable source.

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:

The external-store contract
READgetSnapshot()
Return the current renderable snapshot.
NOTIFYsubscribe(callback)
Tell React that the source may have changed.

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​

How React observes an external source
1component subscribes
2store changes
3store notifies callback
4React calls getSnapshot()
5snapshot changed?
6render if needed

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.

Stable snapshot contract
Store unchanged
getSnapshot() returns the same / Object.is-equal snapshot.
Store changed
Create a new snapshot, then notify subscribers.

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​

External store SSR β†’ hydration flowThe initial browser store state should be compatible with the server snapshot.
1server chooses snapshot
2render HTML
3serialize / recreate initial data
4browser initializes compatible snapshot
5hydrate
6live subscriptions take over

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,
);
}
Scoped external-store pattern
Context
Chooses which store instance this subtree uses.
useSyncExternalStore
Subscribes to that store's changing snapshot.

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​

Does this value need an external store?
It is ordinary local UI state owned by one component/featurePrefer useState / useReducer
React owns it but descendants need broad accessContext may be enough
The underlying source lives outside React and can notify subscribersuseSyncExternalStore is the matching primitive
The problem is remote fetching/cache lifecycleUse a server-state architecture instead

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.

Your external-store responsibilities
subscribe
Notify React when relevant store state may change.
getSnapshot
Return a stable immutable snapshot while unchanged.
getServerSnapshot
Provide compatible initial server/hydration state when SSR is used.

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​

External-store integration sequence
1external source owns data
2React subscribes
3source notifies
4React rereads stable snapshot
5render if snapshot changed

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.