Sub topic 11
Subscribing to browser and external state
This chapter assumes you know useState, useEffect with cleanup, and how a custom hook returns values to a component. It covers reading data that lives outside React, such as the browser's online status, matchMedia, or a store you wrote yourself.
Why useEffect and useState fall short
A common first attempt copies the external value into state and updates it from an event listener:
- Read the value in
useState's initializer. - Subscribe in
useEffect. - Call the setter when the source changes.
This works in simple cases, but it has two problems. The component renders once with a value that may already be stale, because the source can change between the first render and the effect running. Under concurrent rendering, different parts of the tree can also read the source at different moments and show different values on screen. This is called tearing.
useSyncExternalStore solves both problems. React reads the source during render and re-reads it before committing. If the value changed, React re-renders synchronously so the whole tree stays consistent.
The three arguments
useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)subscribe(callback)registerscallbackwith the source and returns a function that unsubscribes. Callcallbackwhenever the source changes.getSnapshot()returns the current value. React calls it often and compares results withObject.is.getServerSnapshot()returns the value to use during server rendering and hydration. It is optional if you never render on the server.
Worked example: online status
import { useSyncExternalStore } from 'react';
function subscribe(callback) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
export function useOnlineStatus() {
return useSyncExternalStore(
subscribe,
() => navigator.onLine,
() => true
);
}subscribe is defined outside the hook, so its identity never changes. If you define it inside the hook, React sees a new function on every render and unsubscribes and resubscribes each time. The server snapshot returns true because the server has no navigator. The client must produce the same value during hydration, then it updates if the real status differs.
Snapshots must be cached
getSnapshot must return the same value when the source has not changed. This hook returns a new object on every call, so React sees a change each time and loops:
// Wrong: a new object on every call
useSyncExternalStore(subscribe, () => ({ online: navigator.onLine }));Return a primitive, or read a stored object that you replace only when the data changes.
A small custom store
The same pattern works for your own module-level state:
import { useSyncExternalStore } from 'react';
let count = 0;
const listeners = new Set();
export const counterStore = {
increment() {
count += 1;
listeners.forEach((listener) => listener());
},
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
getSnapshot() {
return count;
},
};
export function useCounter() {
return useSyncExternalStore(counterStore.subscribe, counterStore.getSnapshot);
}Every component that calls useCounter shows the same count. This differs from the earlier chapter on state isolation, because here the state lives outside React, so hook calls share it.
Exercise
Why does useSyncExternalStore(subscribe, () => ({ width: window.innerWidth })) cause an infinite render loop, and how do you fix it?
Show answer
The snapshot function returns a new object on every call, so Object.is always sees a change and React keeps re-rendering. Return a primitive instead, for example () => window.innerWidth, or store the object and replace it only when the width actually changes.