Skip to content

QuizNot attempted

Why useSyncExternalStore exists

If store.increment() is called from outside React (e.g., a browser devtools console or a non-React event), does the <Counter> component re-render to reflect the new value?
let listeners = [];
let value = 0;
const store = {
subscribe(cb) {
listeners.push(cb);
return () => { listeners = listeners.filter(l => l !== cb); };
},
getSnapshot() {
return value;
},
increment() {
value += 1;
listeners.forEach(l => l());
}
};
function Counter() {
const count = useSyncExternalStore(store.subscribe, store.getSnapshot);
return <div>{count}</div>;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • Yes — useSyncExternalStore is specifically designed to safely subscribe to external mutable stores and re-render on notification
  • useSyncExternalStore subscribes via store.subscribe
  • when increment() notifies listeners, React re-reads getSnapshot(), sees a new value and re-renders, wherever the mutation came from, consistently under concurrent rendering.
  • Not 'invisible to React': the subscription is what makes it visible.
  • Not 'only after an unrelated re-render': the listener schedules the update itself.
  • Not 'React 19 only': the hook shipped in React 18 (with a shim for older versions).