← Back to React, page 3

react-0047 · Hard senior

What is useSyncExternalStore, why was it introduced, and what are the rules for getSnapshot?

useSyncExternalStore subscribes a component to data that lives outside React, such as a store, the browser's online status or a media query, in a way that is safe with concurrent rendering. It takes subscribe, getSnapshot and an optional getServerSnapshot. React reads a consistent snapshot throughout a render to prevent tearing. getSnapshot must return the same value when the data has not changed, or React loops.

Full answer

React state is private to React. Many things are not: a Redux-style store, localStorage, window size, network status, a WebSocket cache. Before React 18 libraries subscribed with useEffect and copied data into state. With concurrent rendering this can produce tearing: the render is interruptible, the store changes in the middle, and two components in the same pass show different values.

const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) solves it. subscribe(callback) registers a listener, calls callback when the store changes, and returns an unsubscribe function. getSnapshot returns the current value. React calls it during render and again before committing, and if the value changed it re-renders synchronously, so the UI never commits an inconsistent view. Updates triggered by this hook cannot be deferred by transitions, which is the price for consistency.

The rules matter. getSnapshot must be pure and fast, and it must return a cached, immutable result: calling it twice without a store change must give an identical value according to Object.is. If it builds a new object each call, React sees a change every time and throws an infinite-loop error. The subscribe function must be stable, defined outside the component or memoized, otherwise React resubscribes on every render.

getServerSnapshot returns the initial value during server rendering and hydration. It must return the same data on both sides. Without it, using the hook on the server throws an error.

You rarely call it directly. State libraries use it inside: Zustand, Redux and Jotai build on it, and it is also the right tool for small hooks such as useOnlineStatus or useMediaQuery.

The example builds a tiny store and an online-status hook.

jsx
import { useSyncExternalStore } from 'react';

function createStore(initialState) {
  let state = initialState;
  const listeners = new Set();
  return {
    getSnapshot: () => state,
    subscribe(listener) {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
    setState(next) {
      state = next;
      listeners.forEach((listener) => listener());
    },
  };
}

const counterStore = createStore({ count: 0 });

function subscribeToOnline(callback) {
  window.addEventListener('online', callback);
  window.addEventListener('offline', callback);
  return () => {
    window.removeEventListener('online', callback);
    window.removeEventListener('offline', callback);
  };
}

function useOnlineStatus() {
  return useSyncExternalStore(
    subscribeToOnline,
    () => window.navigator.onLine,
    () => true
  );
}

function Counter() {
  const state = useSyncExternalStore(counterStore.subscribe, counterStore.getSnapshot);
  return (
    <button onClick={() => counterStore.setState({ count: state.count + 1 })}>
      Count: {state.count}
    </button>
  );
}

export default function App() {
  const online = useOnlineStatus();
  return (
    <div>
      <Counter />
      <p>{online ? 'Online' : 'Offline'}</p>
    </div>
  );
}

The counter lives in a store outside React and the component re-renders when the store notifies it. The online hook reads the browser state, with a fixed value for server rendering. The check clicked the counter once. Rendered result: <div><button>Count: 1</button><p>Online</p></div>

Key points

  • It connects components to external stores safely in concurrent React.
  • It prevents tearing by reading one consistent snapshot per render.
  • getSnapshot must return a stable, cached, immutable value when nothing changed.
  • subscribe must be a stable function that returns an unsubscribe.
  • getServerSnapshot gives the same initial value on the server and during hydration.

Common mistakes

  • Returning a new object from getSnapshot on every call, which causes an infinite loop.
  • Defining subscribe inside the component, which resubscribes on every render.
  • Omitting getServerSnapshot in a server-rendered app.
  • Using useEffect and useState to mirror a store, which allows tearing.
  • Mutating the store state in place so the snapshot reference never changes.

Follow-ups

  • Why can transitions not defer updates that come from useSyncExternalStore?
  • How would you add selector support on top of this hook?
  • What does getServerSnapshot have to do with hydration mismatches?

Tips

  • Define tearing in one sentence with an example. It is the heart of the question.
  • State the snapshot caching rule early. It is the most common bug.
  • Say that you would use a library built on it rather than write a store from scratch.