State management and data fetching · senior
External stores, useSyncExternalStore and building a mini Redux
A store outside React is just state + a reducer (or setters) + a set of listeners; useSyncExternalStore(subscribe, getSnapshot) connects it to React safely, so a component re-renders only when its selected snapshot changes and never shows mixed versions of the store.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Minimal store:
getState(),dispatch(action)(run reducer, notify listeners),subscribe(listener)returning an unsubscribe function. useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?): React callsgetSnapshotand re-renders when the result changes byObject.is.getSnapshotmust return the same value while the store has not changed. Returning a new object each call ({ todos: store.todos }) causes an infinite loop.- Selectors that build new arrays need memoization (
createSelector), otherwise every store change re-renders the component. - Declare
subscribeoutside the component (or memoize it); a new function each render makes React resubscribe. - Why not
useEffect+useStateto subscribe: you miss updates between render and subscribe, and in concurrent rendering different components can show different store versions ("tearing"). React re-checks the snapshot before commit and falls back to a blocking render if the store changed during a transition. getServerSnapshotis required for SSR and must match on server and client.- This is how Redux (
useSelector), Zustand and other libraries bind to React.
The red pen
Common traps: mistake → fix
Mistake: "Subscribe in useEffect and setState"
Fix: tearing and missed updates.
Mistake: "Return
{ ...state }from getSnapshot"Fix: infinite re-render loop.
Mistake: "A selector returning
state.todos.filter(...)is fine"Fix: new array every time; memoize it.
Easy to hard
Questions interviewers ask, easy to hard
- Build a minimal Redux-like store: createStore, subscribe, dispatch.
- Write the React binding with selectors.
- Why use
useSyncExternalStoreinstead ofuseEffect+useState? - What is tearing?
- Why must
getSnapshotreturn a cached value?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.