Sub topic 10
Subscribe to external stores with useSyncExternalStore
This chapter assumes you know function components, useState, and the basics of useEffect with a dependency array. You should also know that React re-renders a component when its state or props change.
The problem: data that lives outside React
Most data in a React app is state or props. Some data is not. The browser tracks whether the network is online. window.matchMedia knows the screen width. A state library such as Redux or Zustand holds data in a store that exists outside any component. These sources are called external stores. They change on their own schedule, and React is not told when that happens.
A component that wants to show this data must do two things:
- Read the current value.
- Re-render when the value changes.
The usual first attempt copies the value into state with an Effect:
import { useState, useEffect } from 'react';
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(true);
useEffect(() => {
function updateState() {
setIsOnline(navigator.onLine);
}
updateState();
window.addEventListener('online', updateState);
window.addEventListener('offline', updateState);
return () => {
window.removeEventListener('online', updateState);
window.removeEventListener('offline', updateState);
};
}, []);
return isOnline;
}This works in simple cases, but it has threeaknesses:
- The first render always uses the placeholder
true. If the browser is actually offline, the user sees the wrong value until the Effect runs and triggers a second render. - The component keeps a copy of data that already has a source of truth. Copies can fall out of date.
- During server rendering, Effects do not run at all. The server output always shows the placeholder.
The built-in solution
React provides useSyncExternalStore for this exact situation. It reads a value from an external store and subscribes to changes, so you do not need useState or useEffect for the copy.
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 arguments:
| Argument | Name | Purpose |
|---|---|---|
| 1 | `subscribe` | Registers a callback with the store and returns a function that removes it. |
| 2 | `getSnapshot` | Returns the current value of the store in the browser. |
| 3 | `getServerSnapshot` | Returns the value to use during server rendering and while hydrating. Optional if you never render on the server. |
A component then uses it like any other hook:
function StatusBar() {
const isOnline = useOnlineStatus();
return <h1>{isOnline ? 'Online' : 'Disconnected'}</h1>;
}The component reads the real value on its first render. It does not need a placeholder or a second render pass.
How it works
React calls subscribe and passes it a callback. When the store changes, your code calls that callback. React then calls getSnapshot again and compares the result with the previous one. If the value differs, React re-renders the component.
The name contains "sync" because React guarantees that every part of the screen shows the same snapshot in one render. With a plain Effect and state copy, one component might show the new value while another still shows the old one for a moment. This kind of mismatch is called tearing. The hook prevents it, which matters when React renders in concurrent mode and can pause and resume work.
Rules for the three functions
Most bugs with this hook come from breaking one of these rules.
getSnapshot must return a stable value
React compares snapshots with Object.is. If two calls return values that are not identical while the store has not changed, React assumes something changed and re-renders. Worse, it may loop and warn that getSnapshot should be cached.
This is a common mistake:
import { useSyncExternalStore } from 'react';
// Wrong: returns a new object on every call.
function useWindowSizeBad() {
return useSyncExternalStore(
subscribe,
() => ({ width: window.innerWidth, height: window.innerHeight })
);
}Each call creates a fresh object, so Object.is always reports a difference. Return primitives, or return the same cached object until the data really changes. For example, read each number separately:
import { useSyncExternalStore } from 'react';
function subscribeToResize(callback) {
window.addEventListener('resize', callback);
return () => window.removeEventListener('resize', callback);
}
function useWindowWidth() {
return useSyncExternalStore(
subscribeToResize,
() => window.innerWidth,
() => 1024
);
}Numbers, strings, and booleans compare by value, so this is safe.
subscribe must be a stable function
If subscribe is defined inside the component, it is a new function on every render. React then unsubscribes and resubscribes after every render. Define it outside the component, as in the examples above. If it must depend on a prop, wrap it in useCallback so it only changes when that prop does.
getServerSnapshot must match on the server and during hydration
Hydration is the step where React attaches to server-generated HTML. The first client render must produce the same output as the server did. For that reason, getServerSnapshot must return the same value on the server and during hydration on the client. After hydration, React switches to getSnapshot and re-renders if the real value differs.
In the online status example the server cannot know whether the user is online, so it assumes true. If you render only in the browser, you can leave the third argument out. If you omit it and the component renders on the server, React throws an error.
The store must change only through its callback
React only checks the snapshot when your subscribe callback fires or when the component renders. If the store changes without calling the callback, the component will not update. Make sure your store notifies subscribers on every change.
Building a small store
You can also use the hook to connect to your own module-level store. This is how many state libraries work internally.
import { useSyncExternalStore } from 'react';
let count = 0;
const listeners = new Set();
const counterStore = {
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
getSnapshot() {
return count;
},
increment() {
count = count + 1;
listeners.forEach(listener => listener());
},
};
export default function Counter() {
const value = useSyncExternalStore(
counterStore.subscribe,
counterStore.getSnapshot,
() => 0
);
return (
<button onClick={counterStore.increment}>
Clicked {value} times
</button>
);
}Notes on this example:
incrementassigns a new number tocountand then notifies every listener. Without the notification loop, the button would not update.subscribeandgetSnapshotare properties of a module-level object, so their identity never changes.- If
countwere an object, you would have to replace it with a new object on each change and return that same object fromgetSnapshotbetween changes. Do not mutate it in place, becauseObject.iswould see the same reference and skip the update.
When to use it, and when not to
Use useSyncExternalStore when the data lives outside React and your component needs to follow it. Typical sources are:
- Browser APIs that emit events, such as online status, media queries, or
localStoragechanges from other tabs. - A store you wrote or a library store that does not already ship a React hook.
- Any mutable value that other code updates and that you want to read during render.
Prefer other tools in these cases:
- If the data is state that your own components own, use
useStateoruseReducer. - If the library already exports a React hook, use that hook. It probably calls
useSyncExternalStorefor you. - If you only need to run code when something changes, for example to start a timer or open a connection, that is synchronization with a system and a normal Effect is the right tool.
The distinction is about direction. useSyncExternalStore brings external data into rendering. An Effect pushes React state out to an external system.
Wrapping it in a custom hook
Components should not know how the subscription works. Put the three functions behind a custom hook, as useOnlineStatus does above. Components then read like this:
function SaveButton() {
const isOnline = useOnlineStatus();
function handleSaveClick() {
console.log('✅ Progress saved');
}
return (
<button disabled={!isOnline} onClick={handleSaveClick}>
{isOnline ? 'Save progress' : 'Reconnecting...'}
</button>
);
}If you later change how online status is detected, you edit one hook and no component changes.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Warning that `getSnapshot` should be cached, or an infinite loop | `getSnapshot` returns a new object or array on each call | Return a primitive, or cache the value until the store changes |
| Component resubscribes after every render | `subscribe` is declared inside the component | Move it outside, or wrap it in `useCallback` |
| Component never updates | The store changes without calling the subscriber callback | Call every listener on every change |
| Error during server rendering | `getServerSnapshot` is missing | Add a third argument that returns a value valid on the server |
| Hydration mismatch warning | `getServerSnapshot` returns different values on server and client | Return the same value in both places |
Exercise
A teammate writes useSyncExternalStore(subscribe, () => ({ theme: localStorage.getItem('theme') })) and the component re-renders in an endless loop with a warning about getSnapshot. What is wrong, and how do you fix it?
Show answer
The getSnapshot function builds a new object on every call. React compares snapshots with Object.is, so it sees a change each time and keeps re-rendering. Return the primitive instead: () => localStorage.getItem('theme'). If an object is truly needed, keep it in a variable and return the same reference until the stored theme actually changes.
Exercise
You move subscribe inside the component so it can use a channel prop. The component now unsubscribes and resubscribes on every render. How do you keep the prop and avoid the churn?
Show answer
Wrap subscribe in useCallback with channel in the dependency array. The function then keeps the same identity until channel changes, and React resubscribes only at that point.
Exercise
Why does the Effect-and-state version of useOnlineStatus show the wrong value on the first render for an offline user, and why does useSyncExternalStore avoid that?
Show answer
The state starts at a placeholder (true), and the Effect only corrects it after the first render has been painted. useSyncExternalStore calls getSnapshot during rendering, so the first render already uses navigator.onLine.