Build the useSyncExternalStore shim and withSelector: missed updates, resubscribing and memoised selections
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
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 2
- code listings
- 5
- edge cases
- 4
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Copying the snapshot into
useStateis the classic bug: the copy goes stale whenevergetSnapshotchanges or the store changes before you subscribe. Where should the value come from on every render?
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.