Sub topic 11
Subscribing to browser and external state
This chapter assumes you know useState and useEffect, the Rules of Hooks, and how to write a custom hook with effect cleanup. It covers how to read state that lives outside React, such as navigator.onLine, matchMedia, or a small global store, and keep a component in sync with it.
The problem with external state
Some values are not owned by React. The browser owns the online status. The window owns its size. A store module you write may own a counter or a user session. React does not know when these change, so a component that reads them once will show stale output.
The familiar fix is useState plus useEffect:
import { useState, useEffect } from 'react';
export function useOnlineStatusNaive() {
const [online, setOnline] = useState(navigator.onLine);
useEffect(() => {
const update = () => setOnline(navigator.onLine);
window.addEventListener('online', update);
window.addEventListener('offline', update);
return () => {
window.removeEventListener('online', update);
window.removeEventListener('offline', update);
};
}, []);
return online;
}This mostly works, but it has three weaknesses:
- Server rendering.
navigatordoes not exist on the server, so the initial state throws there. - Missed changes. The value is read during render, but the subscription starts only after the effect runs. If the value changes in between, the component keeps the old value until the next event.
- Tearing. With concurrent rendering, React can pause a render and resume it later. Different components can then read different values of the same external source in one pass. The screen briefly shows inconsistent data.
useSyncExternalStore exists to solve these problems.
The useSyncExternalStore API
The hook takes three arguments:
subscribe(callback): registerscallbackwith the external source and returns a function that unsubscribes. React callscallbackwhenever the source may have changed.getSnapshot(): returns the current value of the source.getServerSnapshot(): returns the value to use during server rendering and hydration. This argument is optional on the client, but required if the component renders on the server.
Here is the online status hook from this chapter's plan:
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
);
}React calls getSnapshot during render. It also calls it again after subscribing and whenever callback fires. If the new snapshot differs from the old one, the component re-renders. Because React checks the snapshot at commit time as well, a change between render and subscription is not missed, and all components see one consistent value.
Snapshot rules
React compares snapshots with Object.is. Two rules follow from that.
getSnapshotmust return the same value when nothing changed. If it builds a new object or array on every call, React sees a change every time and loops. In development it warns that "The result of getSnapshot should be cached."- Snapshots must be immutable. If you mutate an object in place and return it,
Object.isreports no change and the component does not update.
Primitive values such as booleans, numbers, and strings are always safe. For objects, store one object and replace it only when the data changes.
Keep subscribe stable
React resubscribes whenever the subscribe function it receives is a different function from the previous render. If you define subscribe inside the hook body, the hook unsubscribes and resubscribes on every render. Define it at module level, as the online status example does. If subscribe depends on an argument, wrap it in useCallback.
A hook with an argument: media queries
When the subscription depends on a parameter, subscribe must be created from it and memoized.
import { useCallback, useSyncExternalStore } from 'react';
export function useMediaQuery(query) {
const subscribe = useCallback(
(callback) => {
const mql = window.matchMedia(query);
mql.addEventListener('change', callback);
return () => mql.removeEventListener('change', callback);
},
[query]
);
const getSnapshot = () => window.matchMedia(query).matches;
return useSyncExternalStore(subscribe, getSnapshot, () => false);
}When query changes, subscribe changes, and React unsubscribes from the old query and subscribes to the new one. getSnapshot returns a boolean, so it is safe to call as often as React likes. It does not need memoization because React calls the latest version during each render.
The server snapshot returns false because the server cannot know the viewport. The client's first render during hydration uses this same value, which avoids a mismatch. React then re-renders if the real value differs.
Building your own store
The same API works for any store you write. A minimal store needs a value, a set of listeners, and three functions:
import { useSyncExternalStore } from 'react';
let count = 0;
const listeners = new Set();
export const counterStore = {
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
getSnapshot() {
return count;
},
increment() {
count += 1;
listeners.forEach((listener) => listener());
},
};
export function useCounter() {
return useSyncExternalStore(
counterStore.subscribe,
counterStore.getSnapshot
);
}Any component that calls useCounter re-renders after counterStore.increment(). The store is a plain module, so code outside React can call increment too. State libraries such as Redux and Zustand use this same mechanism.
This example omits the server snapshot. If you render it on the server, React throws an error during server rendering. Add a third argument that returns the initial value, such as () => 0.
Selecting part of a store
If a store holds an object and a component needs one field, read that field in getSnapshot:
import { useSyncExternalStore } from 'react';
let state = { user: { name: 'Ada' }, theme: 'light' };
const listeners = new Set();
function subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
}
export function setState(patch) {
state = { ...state, ...patch };
listeners.forEach((listener) => listener());
}
export function useStoreSelector(selector) {
return useSyncExternalStore(
subscribe,
() => selector(state),
() => selector(state)
);
}A component that calls useStoreSelector((s) => s.theme) gets a string, so it re-renders only when the theme changes. The store replaces state immutably, so state.user keeps its identity when only theme is patched. A selector that returns state.user is therefore also safe. A selector that builds a new object, such as (s) => ({ name: s.user.name }), is not.
When to use it, and when not to
| Situation | Use |
|---|---|
| Value lives in the browser or a module and changes over time | `useSyncExternalStore` |
| One-time setup or side effect, such as starting a timer or logging | `useEffect` |
| Data fetched from a server | A data-loading hook or a data library |
| State that belongs to one component | `useState` |
Use useSyncExternalStore when you read a value that already exists elsewhere. Use useEffect when you perform an action. The online status hook reads a value, so it fits the first case. A debounce timer performs an action, so it does not.
Common mistakes
- Reading a mutable value without notification. If
getSnapshotreturns something that changes with no event, React never learns of the change. The source must call the subscribed callback. - Calling
callbackduring subscribe. Do not call it synchronously insidesubscribeunless the value truly changed. It triggers an extra render. - Forgetting the server snapshot. Components that render on the server need
getServerSnapshot. It must return the same value on the server and during hydration on the client. - Using it for values that should be state. A value only your component changes belongs in
useState.
Exercises
Exercise
Your hook calls useSyncExternalStore(subscribe, () => ({ width: window.innerWidth })) and the component re-renders in an endless loop. Why, and how do you fix it?
Show answer
getSnapshot returns a new object on every call, and React compares snapshots with Object.is, so it always sees a change. Return a primitive instead, such as () => window.innerWidth, or cache one object and replace it only when the width changes.
Exercise
A hook defines function subscribe(callback) { ... } inside its body and passes it to useSyncExternalStore. What goes wrong, and what are two ways to fix it?
Show answer
subscribe is a new function on every render, so React unsubscribes and resubscribes each time. Move subscribe to module level, or wrap it in useCallback with the values it uses as dependencies.