React useSyncExternalStore subscribing to an external data store

React state is great for values React owns. But what about data that lives outside React — a window.matchMedia result, an navigator.onLine flag, a third-party store, or a plain observable singleton that pushes updates? Reaching for useState + useEffect there is a classic source of stale values and “tearing” (two parts of the UI showing different snapshots during a concurrent render). useSyncExternalStore is the built-in hook designed for exactly this job.

The shape of the API

const snapshot = useSyncExternalStore(
  subscribe,        // (onStoreChange) => unsubscribe
  getSnapshot,      // () => current immutable value
  getServerSnapshot // () => value used during SSR/hydration (optional)
);
  • subscribe registers a callback that React calls whenever the store changes; it must return a cleanup function.
  • getSnapshot returns the current value. React calls it during render and after every notification.
  • getServerSnapshot is used on the server and during hydration — omit it only if the component never renders on the server.

A runnable example: track online/offline status

import { useSyncExternalStore } from "react";

// The "store": browser events are its notification mechanism.
function subscribe(onChange) {
  window.addEventListener("online", onChange);
  window.addEventListener("offline", onChange);
  return () => {
    window.removeEventListener("online", onChange);
    window.removeEventListener("offline", onChange);
  };
}

function getSnapshot() {
  return navigator.onLine; // primitive => safe to compare by reference
}

function getServerSnapshot() {
  return true; // SSR has no navigator; pick a sensible default
}

export function ConnectionBadge() {
  const online = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
  return <span>{online ? "🟢 Online" : "🔴 Offline"}</span>;
}

No useEffect, no manual state mirror, no cleanup bookkeeping in the component — the hook owns the subscription lifecycle.

Wrapping it in a reusable hook

Because subscribe and getSnapshot are stable module-level functions, you can wrap the pattern once:

function useMediaQuery(query) {
  const subscribe = useCallback(
    (onChange) => {
      const mql = window.matchMedia(query);
      mql.addEventListener("change", onChange);
      return () => mql.removeEventListener("change", onChange);
    },
    [query]
  );

  const getSnapshot = useCallback(
    () => window.matchMedia(query).matches,
    [query]
  );

  const getServerSnapshot = useCallback(() => false, []);

  return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}

Call it like const isDark = useMediaQuery("(prefers-color-scheme: dark)") and it stays in sync without a single useState.

The gotcha that bites everyone

getSnapshot must return a cached value — the same reference until the store actually changes. This is the #1 mistake:

// ❌ WRONG: a fresh object every call => infinite re-render loop
function getSnapshot() {
  return { x: store.x, y: store.y };
}

// ✅ RIGHT: store the object, return that same reference until data changes
let cache = { x: 1, y: 2 };
function getSnapshot() {
  return cache;
}
function update(x, y) {
  cache = { x, y };      // swap reference only on real change
  listeners.forEach((fn) => fn());
}

React compares snapshots with Object.is. If you hand it a new object or array on every call, it thinks the store changed forever and throws “The result of getSnapshot should be cached to avoid an infinite loop.” Return primitives, or memoize/cache object snapshots and only replace them when data truly changes.

When to reach for it

  • Subscribing to external stores (Redux, Zustand, or your own observable).
  • Browser APIs that change outside React: matchMedia, navigator.onLine, localStorage events, visibilityState.
  • Any source where you’d otherwise write useState + useEffect just to mirror a value into React.

Skip it for state React itself owns — plain useState is simpler. And if you only need to read a value once on mount, you don’t need a subscription at all.

Key takeaways

  • useSyncExternalStore is the tearing-safe bridge between non-React data and React rendering.
  • Keep getSnapshot stable: return primitives or a cached reference, never a fresh object.
  • Provide getServerSnapshot whenever SSR or hydration is in play, or the server render will crash.

It’s not an everyday hook, but when the situation calls for it, it replaces a pile of fragile useEffect glue with one correct, concurrent-safe primitive.