Sub topic 9
Browser state with useSyncExternalStore
This chapter assumes you can write function components and hooks, and that you have seen hydrateRoot and a hydration mismatch. Here you will learn how to read browser-only state, such as navigator.onLine, without causing a mismatch.
The problem
Some values exist only in the browser. navigator.onLine, window.matchMedia, and localStorage are examples. On the server, navigator and window are undefined, so reading them during render either throws or returns a value that differs from what the browser would compute.
You could use the effect pattern from the previous chapter. That works for a value you read once. It is awkward for a value that changes over time, because you must write the subscription, the cleanup, and the initial state yourself.
useSyncExternalStore is the hook for subscribing to a store that lives outside React. It also has a built-in way to handle server rendering and hydration.
The three arguments
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
);
}The hook takes three functions:
| Argument | Role | Runs where |
|---|---|---|
| `subscribe` | Registers a callback and returns a cleanup function | Browser only |
| `getSnapshot` | Returns the current value of the store | Browser |
| `getServerSnapshot` | Returns the value to use for the server HTML and for hydration | Server and during hydration |
getServerSnapshot is what prevents the mismatch. The server renders with true. During hydration, the browser also uses true, even if navigator.onLine is false. The first client render therefore matches the server HTML. After hydration finishes, React calls getSnapshot. If the real value differs, React re-renders with it.
Rules for the snapshot functions
getSnapshotmust return the same value when the store has not changed. Returning a new object each call causes an infinite render loop.getServerSnapshotmust return the same value on the server and during hydration. Choose a sensible default, such as "online".- If you omit
getServerSnapshotand render on the server, React throws an error, because it has no safe value to use.
Choosing between this and an effect
- Use
useEffectwith state for a value you read once, such as the current time. - Use
useSyncExternalStorefor a value that changes and that other code can update, such as network status or a media query.
Exercise
A component calls useSyncExternalStore(subscribe, () => window.innerWidth) and is rendered on the server. What goes wrong, and how do you fix it?
Show answer
There is no getServerSnapshot, so React throws during server rendering, and window is undefined on the server. Add a third argument that returns a fixed default, for example () => 1024. The server and the first client render then use the same value, and React updates to the real width after hydration.