Sub topic 10
Subscribe to external stores with useSyncExternalStore
This chapter assumes you know useState, props, and the basics of useEffect with a dependency array. It covers one case: reading data that lives outside React and keeping the component current when that data changes.
The pattern to avoid
An external store is any source of data that React does not own. Examples are navigator.onLine, window.matchMedia, a Redux-style store, or a third-party state library.
A common first attempt copies the value into state and uses an Effect to keep it in sync:
import { useState, useEffect } from 'react';
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(true);
useEffect(() => {
function update() {
setIsOnline(navigator.onLine);
}
update();
window.addEventListener('online', update);
window.addEventListener('offline', update);
return () => {
window.removeEventListener('online', update);
window.removeEventListener('offline', update);
};
}, []);
return isOnline;
}This works in simple cases, but it has problems:
- The first render always uses the hard-coded
true. If the browser is offline, the user sees the wrong value until the Effect runs and triggers a second render. - The state is a copy of a value that already exists elsewhere. Two sources of truth can disagree.
- Every component that needs the value repeats the subscribe and unsubscribe code.
The built-in hook
React provides useSyncExternalStore for this job. You give it three things:
subscribe: a function that takes a callback, registers it with the store, and returns a function that unsubscribes.getSnapshot: a function that returns the current value of the store on the client.getServerSnapshot: a function that returns the value to use during server rendering and during hydration (attaching React to server-generated HTML).
import { useSyncExternalStore } from 'react';
function subscribe(callback) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
function useOnlineStatus() {
return useSyncExternalStore(
subscribe,
() => navigator.onLine,
() => true
);
}Components then use it like any other hook:
function StatusBar() {
const isOnline = useOnlineStatus();
return <h1>{isOnline ? 'Online' : 'Disconnected'}</h1>;
}There is no state variable and no Effect. React calls getSnapshot during render, so the first render already shows the real value. When the store calls the callback, React calls getSnapshot again and re-renders only if the result changed.
Rules for getSnapshot
React compares snapshots with Object.is to decide whether to re-render. Two rules follow from that.
getSnapshotmust return the same value when the store has not changed. Returning a new object or array on every call causes an infinite render loop.- Snapshots must be immutable. If the store changes, return a new value. Do not mutate the old one.
// Wrong: a new array on every call, so React sees a change every time.
useSyncExternalStore(subscribe, () => store.items.filter(i => i.done));
// Better: read a stable value, then derive during render.
const items = useSyncExternalStore(subscribe, () => store.items);
const doneItems = items.filter(i => i.done);Also define subscribe outside the component, as in the example above. If you define it inside, it is a new function on each render, and React unsubscribes and resubscribes every time.
When to use it
Use useSyncExternalStore when the data lives outside React and can change without React knowing. Do not use it for data that React already owns. Props and state need no subscription, and values computed from them belong in the render, as covered earlier in this tutorial.
If the external system is something you start or stop, such as opening a connection, an Effect is still the right tool. That is the case in the data fetching chapter later in this tutorial.
Exercise
A component reads window.innerWidth into state with useState(window.innerWidth) and updates it from a resize listener in an Effect. Name two problems this has, and say which hook replaces it.
Show answer
The value is copied into state, so there are two sources of truth, and window.innerWidth fails on the server because window does not exist there. A hard-coded initial value would also show a wrong first render. useSyncExternalStore replaces it. subscribe adds and removes the resize listener, getSnapshot returns window.innerWidth, and getServerSnapshot returns a fixed default width.
Exercise
Why does useSyncExternalStore(subscribe, () => ({ width: window.innerWidth })) cause an infinite render loop?
Show answer
getSnapshot returns a new object on every call. React compares snapshots with Object.is, sees a different value each time, and re-renders again. Return a primitive such as window.innerWidth, or a cached object that only changes when the store changes.