Build the useSyncExternalStore shim and withSelector: missed updates, resubscribing and memoised selections

hardAbout 50 minutesUpdated CodingProreactusesyncexternalstoreexternal-storeselectorsmemoizationinternals
Not solved

Share this question

Problem

useSyncExternalStore is how React reads state that lives outside it: Redux, Zustand, a WebSocket cache, window.matchMedia. Before React 18 shipped it, the React team published a shim (use-sync-external-store/shim) built only from useState and effects, plus useSyncExternalStoreWithSelector, which React-Redux's useSelector is built on. Both are short, and every line handles a real bug. Rebuild them.

const ids = useSyncExternalStoreWithSelector(
  store.subscribe,
  store.getState,
  undefined,
  (state) => state.todos.filter((t) => t.done).map((t) => t.id),
  shallowEqualArrays,
);

Ref. UR-1436 · © UIRound · uiround.com/questions/build-the-usesyncexternalstore-shim-and-withselector-missed-updates-resubscribing-and-memoised-selections

Stuck? Take a hint

Try it in the editor

Run your code as often as you like. Submitting it to the full test suite is part of Pro.

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment