Question presented to candidate:
"What is useSyncExternalStore for, and when would you actually reach for it?"
What a strong answer should cover:
- It is the official way to subscribe to state that lives outside React — a module store, a browser API, a websocket cache — and read it safely during rendering.
- Two problems it solves at once: staleness (React never learns a plain variable changed) and tearing (an interruptible render reading a mutable value at two different moments).
- The three arguments:
subscribe,getSnapshot, andgetServerSnapshotfor SSR. getSnapshotmust return a cached value — a fresh object each call is an infinite loop, with React warning that the result should be cached.subscribemust be stable, or React resubscribes on every render.- The deliberate cost: updates from an external store are synchronous and non-interruptible, which is the price of consistency.
- You rarely write it directly — Redux, Zustand, and Jotai all call it internally. You reach for it when integrating a store or browser API yourself.
- Genuine direct uses:
matchMedia,navigator.onLine,localStoragesync across tabs, and a third-party non-React library. - Before React 18, libraries hand-rolled this and could tear under concurrent rendering.
Clarifying questions expected:
- "Is the state actually outside React, or could it just be React state lifted up?"
- "Is this server-rendered?" — that decides whether
getServerSnapshotis mandatory.
Code / implementation expected: Yes — a small store with a correctly cached snapshot, and a browser-API subscription.