Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 132 ยท Context and Shared State

External Stores and useSyncExternalStore

Learn useSyncExternalStore to connect React to data that lives outside React. Build a tiny store, add selectors, wrap browser APIs like online status and matchMedia, and understand tearing.

Most state in a React app lives inside React: useState, useReducer, context. But some data does not. The browser keeps track of whether you are online, how wide the window is, and what the URL is. A third-party library may hold a cache or a model. A module in your own code may keep a plain JavaScript object that many parts of the app read. These are external stores: data whose source of truth is outside React.

React needs a reliable way to read such data during rendering and to re-render when it changes. That is what the useSyncExternalStore hook does. You will rarely call it in application code, since libraries wrap it for you, but understanding it explains how state libraries work, how to wrap browser APIs correctly, and why the "obvious" version with useEffect is subtly broken. It builds on useEffect and context.

Why not just useEffect and useState?

The obvious way to subscribe to something outside React is an effect that copies the value into state:

JSX
function useOnlineStatusNaive() {
  const [isOnline, setIsOnline] = useState(true);
  useEffect(() => {
    function update() { setIsOnline(navigator.onLine); }
    window.addEventListener('online', update);
    window.addEventListener('offline', update);
    return () => {
      window.removeEventListener('online', update);
      window.removeEventListener('offline', update);
    };
  }, []);
  return isOnline;
}

It mostly works, but it has two flaws. First, the initial value is a guess (true), and the real one only arrives after the first render and an extra re-render, so the user may briefly see the wrong thing. Second, with concurrent rendering React can pause and resume a render. If an external value changes in the middle, some components might render with the old value and others with the new one, in the same frame. This inconsistency is called tearing. Copying into state cannot prevent it, because the state copy is only updated later.

useSyncExternalStore solves both. React reads the store directly during render and checks, before committing, that the value did not change. If it did, React re-renders synchronously so the whole screen shows one consistent snapshot.

The API

JSX
const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?);
  • subscribe(callback) registers callback with the store and returns a function that unsubscribes. React calls it when the component mounts and uses the returned function on unmount. When the store changes, you call callback().
  • getSnapshot() returns the current value of the store. React calls it during every render and after each store change.
  • getServerSnapshot() is optional and used for server rendering and hydration; it returns the initial value the server used. Without it, the hook throws on the server.

Two strict requirements come with this:

  1. getSnapshot must return the same value if nothing changed. React compares results with Object.is. If you return a fresh object or array on every call, React thinks the store changed every time and loops.
  2. subscribe must be a stable function. If you define it inside the component, it is a new function every render and React resubscribes each time. Define it outside, or wrap it in useCallback.

Example: a tiny store

The simplest store is a variable with a list of listeners. The pattern below is the same one used by real state libraries, just smaller.

A counter store with useSyncExternalStore

There is no provider and no useState in this app. Both Display components read the module-level variable, and any code can change it, even code that has nothing to do with React, as the second button shows. The only rule is that every change must notify the listeners; otherwise React would never find out.

Mutations must create new snapshots

The counter store is trivial because a number is a primitive. When the snapshot is an object or array, treat it as immutable: every change replaces it with a new value, and getSnapshot returns the stored reference, never a freshly built one.

Here is what goes wrong when getSnapshot builds a new object on every call.

A getSnapshot that returns a new object (fails on purpose)

In the development build React logs "The result of getSnapshot should be cached to avoid an infinite loop" and then fails with "Maximum update depth exceeded". The fix is to return the stored user object itself and to replace that object, never mutate it, when the data changes.

Example: a small store with an object snapshot

A reusable helper makes this reliable. The function below creates a store from an initial state, with getState, setState (which accepts a partial update or an updater function) and subscribe. It never mutates: setState builds a new object with the spread operator.

A createStore helper with a todo list

Add a few tasks, tick some and switch filters. Every component sees the same state because they all subscribe to the same store. This is, in miniature, what a Zustand or Redux store is.

Selectors: subscribe to a slice

The hook above returns the whole state, so every component re-renders on any change to it. A selector picks just the part a component needs, and the component re-renders only when that part changes. With useSyncExternalStore you can build a useStore(selector) hook by passing a getSnapshot that applies the selector. The selector must return something stable (a primitive, or an existing object from the state), because React compares it with Object.is.

Selectors and render counts

Press "Add point" and then "Change name" and read the console. Adding a point logs only ScoreView rendered; changing the name logs only NameView rendered. Compare with context, where every consumer would re-render for either change. That ability to subscribe to a slice is the main reason people use stores instead of context for fast-changing, widely shared state.

A selector that builds a new object or array each time, such as useStore((s) => ({ name: s.name })) or useStore((s) => s.items.filter(...)), returns a different value on every call and triggers the same "should be cached" loop. Select primitives or existing references, and derive the filtered list in the component (with useMemo if it is costly). Libraries add equality helpers for this case.

Browser APIs as stores

The browser is full of external stores: connection state, media queries, window size, visibility, the URL hash. Each fits the same recipe: subscribe adds an event listener and returns its removal; getSnapshot reads the current value. Because the snapshot is a primitive here, caching is automatic.

Online status and a media query

Resize the preview across 480 px or switch your system between light and dark mode while it is open, and the lines update. Notice how short each hook is, and note two details. The inline subscribe for useMediaQuery is a new function on every render, so React resubscribes each render; it works, but moving it into a useCallback keyed on query, or into a module-level function when the query is fixed, is better. And the third argument supplies a safe value for server rendering, where window does not exist.

Because the preview runs in a sandboxed iframe, going offline in your browser's developer tools triggers the offline event, so you can test the first line of this demo. Real projects usually also listen to the visibilitychange event or poll when "online" must be verified, because navigator.onLine only says whether a network interface exists.

Tearing and concurrent rendering

With concurrent features such as transitions React can split a render into small pieces and yield to the browser between them. If a mutable store changes while a render is paused, two components rendered before and after the change would read different values and display an inconsistent screen (a tear).

useSyncExternalStore prevents it by design. During render it records the snapshot, and before committing it calls getSnapshot again. If the value changed, React throws away the work and re-renders synchronously with the new one. The price is that renders caused by store updates cannot be deferred with transitions. That is a deliberate trade for consistency. Because of it, libraries that must keep a screen consistent with a mutable store (Redux's useSelector, Zustand, Jotai) use this hook internally.

If your data can live in React state, prefer React state and avoid this hook. The hook exists for data that React does not own.

When to use it and when not to

Use useSyncExternalStore when

  • you are wrapping a browser API (online status, media queries, matchMedia, localStorage events, the URL);
  • you are writing a store or a library, or integrating one that is not React-aware;
  • an existing non-React model or singleton needs to drive the UI.

Avoid it when

  • the data can simply be state in a component, lifted up, or shared through context;
  • you need to read the value only inside an event handler: just read it there (navigator.onLine) with no subscription;
  • you are tempted to use it to "avoid effects" for ordinary derived data; compute during render instead, see you might not need an effect.

Common mistakes

  • A getSnapshot that allocates. Return stored references or primitives. Never build a fresh object in getSnapshot or in a selector.
  • Mutating the store's state. Replace objects instead of changing them; Object.is otherwise sees no change and components do not update.
  • Forgetting to notify. Change data, then call every listener. Silent changes leave the UI stale.
  • A subscribe created in render. It causes unsubscribe and resubscribe on every render. Define it outside the component or memoize it.
  • Not unsubscribing. Always return a cleanup from subscribe, otherwise listeners leak.
  • Forgetting the server snapshot. On the server window and navigator do not exist, so provide getServerSnapshot and keep it equal to what the client's first render will read, or hydration warns.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the tearing problem refer to?

    Tearing is when part of the UI renders with an old value of an external store and part with a new one. useSyncExternalStore re-renders synchronously to avoid it.
  2. 2. What must getSnapshot do when the store has not changed?

    React compares snapshots with Object.is. Returning a new object every time looks like a change and causes an infinite loop.
  3. 3. Why should subscribe be defined outside the component (or memoized)?

    React treats a changed subscribe function as a new subscription, so an inline function causes needless resubscription on each render.
  4. 4. In a hook built on top of a store, which selector is a problem?

    The last selector returns a new object on every call, so React sees a change each time. Select a primitive or an existing reference instead.
  5. 5. Which situation is a good fit for useSyncExternalStore?

    The media query result is external data with change events. Form text and derived totals belong in React state or in render, and a theme fits context.

Summary

  • External stores hold data outside React; useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) connects them safely.
  • subscribe registers a callback and returns an unsubscribe function; getSnapshot must return a cached, stable value.
  • Store updates must produce new immutable snapshots and notify every listener.
  • Selectors let components subscribe to a slice, so they re-render only when that slice changes.
  • Browser APIs such as navigator.onLine and matchMedia become short, correct hooks with this recipe.
  • The hook prevents tearing in concurrent rendering at the cost of making store-driven updates synchronous; prefer plain React state when the data belongs to React.

Next: State Management Libraries