React Foundations ยท State

Subscribing to an external store

Subscribing to an external store with useSyncExternalStore

Reading an external store

Some state does not belong to a component. It lives in a module-level cache, a browser API, or a subscription that other code also writes to. Copying that value into useState goes stale the moment the store changes underneath you.

useSyncExternalStore lets a component read such a store directly and re-render whenever it changes:

const value = useSyncExternalStore(subscribe, getSnapshot);

It takes two functions:

  • subscribe registers a callback and returns an unsubscribe function. React calls the callback whenever the store changes, then re-reads the snapshot.
  • getSnapshot returns the store's current value. It must return the same value until the store actually changes.
let count = 0;
const listeners = new Set();

function subscribe(listener) {
  listeners.add(listener);
  return () => listeners.delete(listener);
}

function getSnapshot() {
  return count;
}

When the store changes you notify every listener, and each subscribed component re-renders with the new snapshot. React never owns the value; it only subscribes to it.

Your job is to render a module-level store through the hook. The component lives in App.jsx.

Challenge

A counter lives outside React, and the screen has to stay in step with it. Export an App component from App.jsx that defines a module-level counter store and reads it with useSyncExternalStore. Render a single button labelled Count: <n>, and have clicking it advance the store by one.

The Test clicks the button once and expects it to read Count: 1. The starter renders a fixed label and never subscribes, so the Test fails.

App.jsx
export function App() {
  return <button>Count: 0</button>;
}

No test run yet

The Test is hidden. Run it to check the Challenge โ€” you only see the result, never the test source.