Sub topic 9
Browser state with useSyncExternalStore
This chapter covers how to read browser-only state, such as navigator.onLine, without causing a hydration mismatch. It assumes you know useState, useEffect, and the basics of hydrateRoot from earlier chapters. It also assumes you know why the server and the first client render must produce the same HTML.
The problem: state that lives outside React
Some values do not belong to any React component. They live in the browser or in a module-level store, and they can change at any time. Examples:
navigator.onLine, which says whether the browser has a network connection.window.matchMedia(...), which reports whether a CSS media query matches.- A global store such as a Redux-style store or a custom event emitter.
These values are called external stores. React does not own them, so it needs a safe way to read them and to find out when they change.
On the server there is no window and no navigator. If a component reads navigator.onLine during render, the server throws a ReferenceError. If you guard the read with typeof window !== 'undefined', the server renders one thing and the browser renders another. That is a hydration mismatch.
// Broken on the server, and a mismatch if you guard it.
function StatusBar() {
const isOnline = navigator.onLine; // ReferenceError during server rendering
return <p>{isOnline ? 'Online' : 'Offline'}</p>;
}You could fix this with useState and useEffect, as in the earlier chapter on client-only effects. That works, but it has two costs. The component renders once with a placeholder, then again with the real value. Also, you have to write the subscribe and unsubscribe logic yourself, and it is easy to miss a change that happens between the first render and the effect running.
useSyncExternalStore handles both problems.
How useSyncExternalStore works
The hook takes three arguments:
| Argument | Purpose |
|---|---|
| `subscribe` | Registers a callback that the store calls on change. Returns a function that unsubscribes. |
| `getSnapshot` | Returns the current value on the client. |
| `getServerSnapshot` | Returns the value to use on the server and during hydration. |
Here is the hook from the chapter's example, wrapped in a custom hook.
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
);
}Each argument does one job:
subscribereceives a callback from React. You call that callback whenever the store changes. React then callsgetSnapshotagain and re-renders if the result differs.getSnapshotruns in the browser. It reads the live value.getServerSnapshotruns on the server, and also on the client during hydration. It must not touch browser-only APIs. Here it returnstrue, which means "assume online."
You can use the custom hook like any other.
function StatusBar() {
const isOnline = useOnlineStatus();
return <p>{isOnline ? 'Online' : 'Offline'}</p>;
}Why the third argument prevents a mismatch
The key rule is that hydration uses getServerSnapshot, not getSnapshot. During hydration, React calls getServerSnapshot so the first client render matches the server HTML. Once hydration finishes, React calls getSnapshot. If the real value differs from the server snapshot, React schedules a second render with the real value.
The sequence below shows this.
A user who is offline sees "Online" for a moment, then the page corrects itself. That brief flash is the cost of a server that cannot know the browser's state. You choose the server snapshot to make that flash as harmless as possible.
What happens if you omit getServerSnapshot
If you leave out the third argument and render on the server, React throws an error. The message says that getServerSnapshot is required for server rendering. React does this on purpose. Without a server value, it cannot produce HTML, and a guess at one would risk a mismatch.
If the snapshot differs between the server and the first client render, React reports a hydration mismatch. This can happen when you pass a getServerSnapshot that returns a different value than the server used. Both sides must agree.
Gotchas
getSnapshot must return a cached value
React calls getSnapshot many times and compares results with Object.is. If it returns a new object each time, React sees a change on every call and loops.
// Wrong: a new object on every call causes an infinite loop.
useSyncExternalStore(subscribe, () => ({ online: navigator.onLine }), () => ({ online: true }));Return a primitive, or return the same object reference until the data changes. In development, React warns with "The result of getSnapshot should be cached to avoid an infinite loop."
Define subscribe outside the component
If you create subscribe inside the component, React gets a new function on each render. It then unsubscribes and resubscribes every time. Define it at module level, or wrap it in useCallback, when it depends on props.
Pick the server snapshot deliberately
The server snapshot is a design choice. For navigator.onLine, true is reasonable, because most visitors are online. For a media query like "prefers dark mode," there is no safe default. A wrong guess can cause a visible flash of the wrong theme. In that case consider rendering the same neutral output on both sides, or use a CSS-only approach.
Do not use it for values that never change
If a value is read once and never updates, such as the current time at page load, useSyncExternalStore adds nothing. Use the effect approach from the earlier chapter.
Choosing between the two approaches
| Situation | Better choice |
|---|---|
| A value the browser changes over time, with an event to listen for | `useSyncExternalStore` |
| A global store shared across components | `useSyncExternalStore` |
| A value set once after mount, such as a timestamp | `useState` with `useEffect` |
| Output that should appear only in the browser | `useState` with `useEffect` |
Many state libraries already use useSyncExternalStore internally, so you may get this behavior without writing the hook yourself. Check whether the library lets you supply a server snapshot or initial state.
Exercises
Exercise
A component calls useSyncExternalStore(subscribe, () => window.innerWidth) and is rendered with renderToPipeableStream. What goes wrong, and how do you fix it?
Show answer
The server has no window, and the third argument is missing, so server rendering fails. Add a getServerSnapshot that returns a fixed width, for example () => 1024. The client hydrates with that value, then React re-renders with the real width if it differs.
Exercise
Why does useSyncExternalStore(subscribe, () => ({ online: navigator.onLine }), () => ({ online: true })) cause an infinite loop, and what is the fix?
Show answer
Each call to getSnapshot returns a new object, so Object.is reports a change every time and React keeps re-rendering. Return the primitive navigator.onLine directly, or cache the object and return the same reference until the value changes.
Exercise
During hydration, which function does React call to read the value, getSnapshot or getServerSnapshot? Why?
Show answer
getServerSnapshot. The first client render must match the server HTML, and the server produced its HTML from getServerSnapshot. After hydration React calls getSnapshot and re-renders if the value differs.