Skip to the page

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.

The 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 calls getSnapshot and re-renders when the result changes by Object.is.
  • getSnapshot must 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 subscribe outside the component (or memoize it); a new function each render makes React resubscribe.
  • Why not useEffect + useState to 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.
  • getServerSnapshot is 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

  1. Build a minimal Redux-like store: createStore, subscribe, dispatch.
  2. Write the React binding with selectors.
  3. Why use useSyncExternalStore instead of useEffect + useState?
  4. What is tearing?
  5. Why must getSnapshot return a cached value?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview