Skip to content
Tech Interview Prep
Technical interview guideNew

React State Management

Where React state should live and which tool should own it: local state, lifting, Context, Redux Toolkit, Zustand, and the server-state libraries that replace hand-rolled caches. Covers the trade-offs interviewers use to separate people who have shipped a large React app from people who have only read about one.

Read
14 min
Practice MCQs
25
Interview Q&A
25
Edition
v1
Editorial status
Reviewed
Relevant for
Frontend Engineer

Scope: React 19 and 18, Redux Toolkit 2.x, Zustand 5.x, TanStack Query 5.x, React Router 7, Next.js 15 — checked against current docs as of early 2025..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

How do you decide whether a piece of state should be local, lifted to a parent, or global?

Answer

The 90-second answer. Three questions, in order: who reads it, who writes it, how often it changes. State belongs to the closest common ancestor of every component that reads it: that is the ownership rule, and it is what "lift state up" means. Update frequency then picks the mechanism, because the cost of a state update is its re-render fan-out: React re-renders the component that owns the state and, by default, its whole subtree. A context value change re-renders every consumer, memo or not. So a value changing 120 times a second and read by 400 components is a different design problem from a theme that changes twice a session, even though both look "global".

StateReadersWritesHome
dropdown openthe dropdownrareuseState in the dropdown
selected row idtable + detail panerarelift to their common parent
theme, localewhole apprarecontext
cart linesheader, list, checkout~1/interactionexternal store with selectors
order list from APIseveral screensrefetchserver cache (TanStack Query), not a store
cart totalheader—derive during render, never store

Lifting, then the two escapes from prop drilling.

// React 18. Lowest common ancestor owns the state.
function SearchPage() {
  const [query, setQuery] = useState('');
  return (<>
    <FilterPanel query={query} onQueryChange={setQuery} />
    <Results query={query} />
  </>);
}

When the LCA is far above the readers, context removes the plumbing. Pass children from above so the provider's own state change does not re-render the tree it wraps:

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('dark');
  return <ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>;
}
// <ThemeProvider><App /></ThemeProvider> — App's element is stable, so it bails out.

When the value is both widely read and frequently written, context is the wrong tool: every consumer re-renders on every write. Move it to an external store and subscribe to a slice, so a component re-renders only when its selection changes:

const total = useStore(s => s.cart.total); // re-renders only when total changes

Failure modes, and how you catch each.

  1. High-frequency state in context. A drag handler writing pointer position to a context read by 400 components: at 120 Hz that is 48,000 component renders per second (hypothetical, but the arithmetic is the point). Detect: React DevTools Profiler shows a commit on every pointermove with the whole consumer list in the flame chart. Fix: keep it local, or use a store with selectors.
  2. Prop drilling through six layers. Detect: components that accept props they only forward and never read. Fix: lift to the LCA, use context for the plumbing, or pass children so the middle layers never see the value.
  3. Server data in a global store. Detect: hand-written invalidation code, and lists that go stale after a mutation elsewhere. Fix: a server cache owns it; the store owns client state only.
  4. Duplicated state. Two useState holding the same fact drift as soon as one update path misses the other. Detect: a bug that only appears after a specific navigation order. Fix: one owner, everything else derived during render.

When not to lift. If only one component reads and writes it, lifting it is a regression: you have widened the re-render surface and added props for nothing. Colocate first; lift only when a second reader appears. And when the identity of the thing changes (a different user, a different draft) reset with key rather than syncing state in an effect.

Curated: · Written: · Reviewed:

Q&A-2

Two sibling components need to stay in sync. Walk me through lifting the state up: what it costs, and when you'd reach for composition instead?

Answer

The 90-second answer. Lifting state up means moving a piece of state to the closest common ancestor of every component that reads or writes it, then passing the value down as a prop and the update up as a callback. It is the default answer to "two siblings must agree", and it is not the same as "put it in the root": the target is the closest common ancestor, because the owner defines the re-render scope. Two costs come with it: prop drilling through components that never read the value, and a re-render of the owner's entire subtree on every change. Composition beats lifting when the state is only needed by one subtree and the other children are expensive or independent: pass those children in as JSX so their element identity stays stable and React skips them.

Mechanics. State lives in the owner; the children become controlled.

// React 18.3 / 19
function ProductPage() {
  const [query, setQuery] = useState('');            // owner: closest common ancestor
  return (
    <>
      <SearchBox value={query} onChange={setQuery} />  {/* writes up */}
      <ResultList query={query} />                     {/* reads down */}
      <Footer />                                       {/* neither, still re-renders */}
    </>
  );
}

setQuery is stable across renders, React guarantees the setter identity from useState, so passing it down does not by itself break memo on SearchBox. Passing () => setQuery(x) inline does.

What it costs. A state update re-renders the owner and, by default, every descendant. React does not compare props to decide. Typing one character into SearchBox produces one commit in which ProductPage, SearchBox, ResultList and Footer all render. Ten characters is ten commits. If the owner's subtree is 400 components, that is 4,000 component renders for a string two of them read. (Figures are illustrative; the Profiler shows the real count per commit.) React 18 batches updates inside event handlers, promises and timeouts, so three setQuery calls in one handler are one commit, not three.

ApproachOwnerRe-render scopeMain cost
Lift to common ancestorclosest common ancestorowner's whole subtreedrilling + wide renders
Composition (children)the component that needs itthat component onlyelement identity must stay stable
Contextproviderevery consumer of that contextall consumers re-render on any change
External storestoresubscribed selectorsindirection, extra dependency

When composition beats lifting. If the only reason to lift is that a wrapper must coordinate children, invert it: keep the state in the wrapper and pass the independent subtree in as children.

function ProductPage() {
  return (
    <SearchAndResults>   {/* owns query */}
      <Footer />         {/* element created by ProductPage, which never re-renders */}
    </SearchAndResults>
  );
}

SearchAndResults re-renders on every keystroke, but its children prop is the same element object it received last time, so React bails out of re-rendering Footer. The same holds for memo-wrapped children and useMemo'd elements. It fails the moment you wrap the child in a new element or a new inline function each render.

Failure modes.

  1. Lifting too far. State in App that one branch needs; every keystroke re-renders the whole tree. Detect: the Profiler commit lists components that never read the value.
  2. Drilling through non-consumers. Four layers accept and forward a prop they never use. Detect: a component's props are a superset of what its body reads.
  3. Storing derived state. Keeping filteredItems in state next to query gives two sources of truth and the list goes stale. Detect: a useEffect whose only job is to write state from other state.
  4. Inline props defeating memo. onChange={() => setQuery(q)} or style={{...}} creates a new reference each render, so a memo child re-renders anyway. Detect: the memo child still appears in the commit.

Curated: · Written: · Reviewed:

Q&A-3

A value is needed five levels deep in the component tree. Walk me through how you choose between prop drilling, Context, and an external store.

Answer

The 90-second answer. Five levels is not the deciding factor. Props are fine at any depth if one leaf reads the value and the components in between are stable: drilling costs you a re-render of every intermediate when the value changes, and memo fixes that. What actually decides it: how many components read the value, how often it changes, and whether anything outside React needs to read or write it.

My default order:

  1. Props while the fan-out is small and the value changes rarely. Explicit, no dependency, and the intermediates memoize away.
  2. Context when the value is app-wide and read by many scattered components: theme, locale, signed-in user, feature flags. Split by update frequency and memoize the value object.
  3. An external store (Zustand, Redux Toolkit, Jotai) when consumers need different slices of a fast-changing value, when writes originate outside React (a websocket, an imperative canvas API), or when you need devtools, middleware or persistence.

Context is transport, not a state manager: the state still lives in useState/useReducer above the provider. And if the value comes from the server, none of the three: that is TanStack Query or a server fetch.

Why Context re-renders everything. A consumer subscribes to the context object, not to a field. When the provider's value changes identity, React re-renders every consumer of that context, and React.memo does not stop it: memo compares props, and context propagation bypasses that comparison. There is no selector granularity in built-in Context.

// React 18.3
const CursorContext = createContext(null);

function CursorProvider({ children }) {
  const [pos, setPos] = useState({ x: 0, y: 0 });
  useEffect(() => {
    const onMove = (e) => setPos({ x: e.clientX, y: e.clientY });
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, []);
  // new object every render; setPos is stable but the literal is not
  return <CursorContext.Provider value={{ pos, setPos }}>{children}</CursorContext.Provider>;
}

const Row = memo(function Row() {
  const { pos } = useContext(CursorContext); // memo does NOT prevent this re-render
  return <div>{pos.x}</div>;
});
Prop drillingContextExternal store
Re-render scopestate owner's subtree, minus memoized branchesevery consumer of that contextcomponents whose selected slice changed
Selector granularityn/anoneyes
Read/write outside Reactnonoyes (getState, subscribe)
Devtools, middleware, persistencenonoyes
Costexplicit, zero depsprovider + split contextsdependency, store lifecycle, SSR isolation

Worked estimate. A cursor tracked on mousemove fires ~60 events/s, so the provider commits ~60 times/s. With 200 consumers that is ~12,000 consumer renders per second. A selector store where 3 components read pos.x re-renders those 3: ~180/s, a ~66× reduction. Same value, same tree: the difference is subscription granularity.

Failure modes.

  1. Context value identity churn. The provider re-renders for an unrelated reason and an inline value={{...}} re-renders all consumers. Detect: React DevTools Profiler shows a context change as the render cause on components whose props did not change. Fix: useMemo the value, or move the provider below the state that churns.
  2. One context for everything. A theme toggle re-renders components that only read auth. Detect: commit count on a theme switch. Fix: one context per update frequency.
  3. Store without selectors. useStore() returning the whole state re-renders on every field change: Context's problem with an extra dependency. Detect: same profiler check.
  4. Module-level store singleton under SSR. Two concurrent requests share state and one user sees another's data. Detect: a request-scoped assertion in an integration test. Fix: create the store per request and pass it through a provider.

React Compiler removes most manual memo work in the prop-drilling case, but it does not add selector granularity to Context: a consumer whose context value changed still re-renders.

Curated: · Written: · Reviewed:

Q&A-4

What does React Context actually re-render when its value updates, and why does the identity of that value decide it?

Answer

The 90-second answer. Context is a subscription, not a store. React keeps the current value on the provider fiber, and every component that calls useContext(ThatContext) subscribes to it. When the component that owns the provider re-renders and produces a value that is not Object.is-equal to the previous one, React re-renders every consumer of that context, not just the ones reading the field that changed, and not memoizable away. There is no selector and no field-level diff. If the new value is the same reference, React bails out of propagating and no consumer re-renders.

So the value's identity is the update signal, which is why value={{ theme, count }} is the single most common context bug:

// React 18/19
const ThemeContext = createContext(null);

function App() {
  const [count, setCount] = useState(0);
  const value = { theme: 'dark', count };        // fresh object every render
  return (
    <ThemeContext.Provider value={value}>
      <Counter onClick={() => setCount(c => c + 1)} />
      <Sidebar />                                 {/* only reads value.theme */}
    </ThemeContext.Provider>
  );
}

Every setCount re-renders App, which produces a new value, which re-renders Sidebar even though theme never moved. useMemo(() => ({ theme, count }), [theme, count]) fixes the identity only if the dependency list is honest; drop count from it and Sidebar stops re-rendering but also starts reading a stale count. That trade (correct deps, or a stale read) is the thing interviewers are listening for.

StepProvider valueObject.is(prev, next)Consumers re-render
toggle theme'light' → 'dark'falseall consumers
parent re-render, useMemo([theme])same objecttruenone
parent re-render, inline literalnew object, identical contentsfalseall consumers

Splitting is usually better than memoizing. useReducer's dispatch and useState's setter are stable across renders, so a context that carries only the dispatch function never invalidates its consumers:

const TodosContext = createContext(null);      // changes on every edit
const DispatchContext = createContext(null);   // stable reference

function TodosProvider({ children }) {
  const [todos, dispatch] = useReducer(reducer, []);
  return (
    <TodosContext.Provider value={todos}>
      <DispatchContext.Provider value={dispatch}>
        {children}
      </DispatchContext.Provider>
    </TodosContext.Provider>
  );
}

Two things people get wrong in the other direction. First, React.memo does not stop a context-driven re-render: memo compares props, and the context read is not a prop. Second, the provider does not re-render its whole subtree just because its value changed: if children arrive as a stable element reference from above, that subtree is skipped, and only the components that actually call useContext re-render underneath it.

Failure modes. (1) Inline object or arrow function in value: detect with the DevTools Profiler's "Highlight updates": consumer subtrees commit after an unrelated setState. (2) A memoized value used as an effect dependency: contents equal, identity new, so the fetch runs twice. Detect in the Network tab, or by comparing render and effect counts side by side. (3) High-frequency state (mouse position, every keystroke) fanned out to a large consumer set: with, say, 2,000 consumers at roughly 0.05 ms each, that is ~100 ms of work per keystroke. Numbers illustrative, but the shape is why typing feels laggy.

When not to use it. If the value changes faster than it is read, or only a handful of consumers need each field, an external store read through useSyncExternalStore with a per-component selector re-renders only the subscribers whose selected slice changed. Context has no equivalent, and no amount of useMemo gives you one.

Curated: · Written: · Reviewed:

Q&A-5

Your context provider passes `{ state, dispatch }` as a single value. Walk me through when splitting it into a separate state context and dispatch context actually changes what re-renders, and when it is not worth doing.

Answer

The 90-second answer. A context consumer re-renders when the context value changes by Object.is. Pass value={{ state, dispatch }} and that object is a new identity on every provider render, so every consumer re-renders: including the buttons that only ever call dispatch and never read state. Splitting into two providers fixes exactly that half. useReducer's dispatch and useState's setter have a stable identity across renders (React documents this as a guarantee), so a DispatchContext whose value is the bare function never changes, and dispatch-only consumers stop re-rendering when state changes.

What the split does not fix: state consumers. Every component reading StateContext still re-renders on every state change, because the state object is a new reference. If you need per-slice subscription, you need several state contexts or an external store with selectors.

// React 18/19
const TasksContext = createContext(null);
const TasksDispatchContext = createContext(null);

function TasksProvider({ children }) {
  const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
  return (
    <TasksContext.Provider value={tasks}>
      <TasksDispatchContext.Provider value={dispatch}>
        {children}
      </TasksDispatchContext.Provider>
    </TasksContext.Provider>
  );
}

function AddTask() {
  const dispatch = useContext(TasksDispatchContext);
  // context never re-renders this: dispatch identity is stable
  return <button onClick={() => dispatch({ type: 'added' })}>Add</button>;
}

What actually re-renders.

Consumer readsOne context {state, dispatch}Split contexts
state onlyevery state changeevery state change
dispatch onlyevery state changenever, from context
bothevery state changeevery state change

Context is not the only reason a component re-renders: a parent re-render still does, unless the subtree is memoized or passed as children. The win here is the middle row, and it is usually the row that dominates: forms, toolbars, per-row delete buttons. On a board with, say, 200 rows, each row's delete button is a dispatch-only consumer; without the split, adding one task re-renders all 200 buttons.

The trap that undoes it. Wrapping dispatch in anything per-render reintroduces the unstable identity:

// broken: new object every render, dispatch-only consumers re-render again
<TasksDispatchContext.Provider value={{ dispatch, addTask }}>

useMemo(() => ({ dispatch, addTask }), [dispatch]) restores it, but the honest fix is to pass the bare dispatch and let consumers build their own action objects.

When it is unnecessary.

  • Every consumer reads state anyway. Two contexts, two useContext calls, no re-render saved.
  • The provider value is already stable: a ref, a constant, or a useMemo'd object that only changes when the data changes.
  • State changes rarely and the subtree is small. Two extra providers are indirection; measure before adding them.
  • You already use an external store with selectors (Zustand, Redux, Jotai). The selector subscription already prevents the re-render, so splitting contexts is redundant.

Failure modes and detection.

  1. Split, but the state value is still inline. value={{ tasks }} re-renders every state consumer on every provider render, even when tasks is unchanged. Detect: React DevTools Profiler with "Highlight updates when components render" shows commits where the state reference is identical.
  2. Split, and the slow list is still slow. The state context re-renders all consumers. Detect: a render counter on a leaf that reads one field; if it increments on unrelated updates, the split was the wrong tool.
  3. Dispatch wrapped per render. Covered above. Detect: the dispatch-only consumer re-renders again after the change.

Curated: · Written: · Reviewed:

Q&A-6

You're holding app state in Context plus useReducer instead of a store library. What do you actually give up by not using one, and when does that trade flip?

Answer

The 90-second answer. Context plus useReducer is a state container, not a subscription system. The reducer gives you ergonomics (actions, one pure function you can unit-test outside React) and Context gives you a way to reach that state without prop drilling. What you don't get is fan-out control. A context value is compared by Object.is when the provider re-renders, and when it changes, React re-renders every consumer in the subtree. There is no selector, no per-component equality check, no way for a component to say "I only read items.length". A store library's core job is exactly that: each component subscribes to a derived value and re-renders only when that value changes. The rest of what you give up (DevTools replay, middleware, persistence, undo) all follows from keeping one serializable action log. So the decision is whether you have enough independent consumers, with enough update independence, to need the subscription model.

// React 18.3
const CartState = createContext(null);
const CartDispatch = createContext(null);

function CartProvider({ children }) {
  const [cart, dispatch] = useReducer(cartReducer, emptyCart);
  // dispatch identity is stable across renders; the cart object is not
  return (
    <CartDispatch.Provider value={dispatch}>
      <CartState.Provider value={cart}>{children}</CartState.Provider>
    </CartDispatch.Provider>
  );
}

function AddToCart({ id }) {          // does not re-render when the cart changes
  const dispatch = useContext(CartDispatch);
  return <button onClick={() => dispatch({ type: 'add', id })}>Add</button>;
}

Splitting state from dispatch is the highest-value trick here: dispatch-only components drop out of the fan-out entirely. It is not a substitute for selectors: anything that reads state still re-renders on every cart change.

Mechanism. React-Redux v8 and later implements useSelector on useSyncExternalStore. The store keeps a subscriber list; dispatch notifies every subscriber; each selector re-runs; the component re-renders only if the selected result fails the equality check (reference equality by default). Context has no subscriber list, the provider's children are the subscribers, so granularity is all-or-nothing.

Context + useReducerRedux Toolkit + react-redux
Update granularityevery consumer of the changed providercomponents whose selected value changed
Dispatch from non-React code (socket, analytics)no: must be inside the treeyes, store.dispatch from anywhere
Action log, replay, time travelnone; state snapshots in React DevToolsDevTools log, replay, dispatch from the tool
Middleware, persistence, undohand-rolledmiddleware, RTK Query, redux-persist, redux-undo
Reducer unit-testable outside Reactyesyes

Trace (hypothetical figures). A listing page mounts 240 AddToCart buttons reading one combined context. One quantity change produces new cart state, the provider re-renders, all 240 consumers re-render: roughly an 18 ms commit on a mid-tier laptop, nearly all of it wasted. Under react-redux with useSelector(s => s.cart.qty[id]), the same dispatch runs 240 cheap selectors and re-renders the 2 components whose selected value changed.

Failure modes.

  1. value={{ cart, dispatch }} allocates a new object on every provider render, so every consumer re-renders even when the cart is untouched. Detect: Profiler commit counts spike when unrelated parent state changes.
  2. React.memo does not block context updates: the row re-renders anyway and people conclude React is slow. Detect: Profiler's "why did this render" says "context changed".
  3. One monolithic provider: a keystroke in a search input re-renders every consumer, so commit cost scales with page size rather than with subscribers. Detect: commit duration grows with the tree, for an action unrelated to what is being read.
  4. No non-React dispatch. The socket handler reaches for a module-level variable plus an event emitter: an ad-hoc store with none of the tooling. Detect: a dispatchRef exported from a module.

When the trade flips. Many independent readers, fine-grained updates, dispatch from outside React, or a real need for replay/persistence/undo: add the store. A dozen consumers, coarse updates, one screen owning the state: Context plus useReducer is less machinery, and on the server it is per-request by construction, whereas a module-level store leaks state between requests unless you build it per request.

Curated: · Written: · Reviewed:

Q&A-8

Walk me through the Redux data flow, and why reducers have to be pure: what actually breaks when they aren't?

Answer

The 90-second answer. Redux is one store with a one-way loop: dispatch(action) → the store calls the root reducer with the current state and the action → the reducer returns the next state → the store replaces its state and notifies subscribers → React re-renders whatever selected a changed slice. The reducer is the only place state changes, and it must be a pure function of (state, action): same inputs, same output, no mutation of the input, no side effects, no Date.now() or Math.random().

Two guarantees rest on that. Re-render decisions are reference comparisons: useSelector compares the selected value with Object.is by default, so a reducer that mutates and returns the same object tells React nothing changed. The action log is replayable: DevTools time travel, SSR hydration and optimistic-update rollback all re-run the same actions from an earlier state and expect the same result.

// Redux 5.x / react-redux 9.x
dispatch({ type: 'todos/added', payload: 'a' });
// 1. store.currentReducer(store.currentState, action)  — once per dispatch
// 2. combineReducers routes to todosReducer(todos, action)
// 3. store.currentState = nextState
// 4. every subscriber runs; useSyncExternalStore schedules a React render
// 5. useSelector re-runs the selector; Object.is(prev, next) decides the re-render

Now the impure version:

function todos(state = [], action) {
  switch (action.type) {
    case 'todos/added':
      state.push(action.payload);   // mutates the store's array
      return state;                 // same reference
    default:
      return state;
  }
}

store.getState().todos is ['a'], but useSelector(s => s.todos) returns the same array reference it returned before, Object.is is true, and the component never re-renders. The store is right and the screen is wrong: the worst class of bug to chase, because every log you print from the store looks correct.

Time travel shows the same defect from the other side. Dispatch add 'a', add 'b', add 'c'. A pure reducer leaves three distinct arrays in the DevTools history, so jumping to action 2 shows ['a','b']. The mutating reducer has one array mutated three times; all three history entries point at it and all three render ['a','b','c']. Replay and rollback are gone.

ImpuritySymptomDetection
Mutating stateStore updates, UI doesn'tRTK's immutableCheck middleware (dev default); redux-immutable-state-invariant
Date.now(), Math.random(), crypto.randomUUID()Replay and SSR hydration produce different stateHydration mismatch warnings; DevTools replay diverges
Side effects (fetch, nested dispatch)Redux throws Reducers may not dispatch actions; duplicate requestsThe throw itself
Non-serializable values (Date, Map, class instance)DevTools can't persist or replayRTK's serializableCheck (dev default)

The Immer nuance. Redux Toolkit's createSlice uses Immer, so state.push(x) inside a slice reducer is legal: Immer records the mutation on a draft and returns a new object. That is syntax, not impurity. It only covers plain objects, arrays, Map and Set; mutating a class instance or a Date inside a draft is a real mutation that leaks out. Immer also freezes state in development (autoFreeze), so a stray mutation throws in dev and silently corrupts in prod.

Side effects belong in thunks, createAsyncThunk, or createListenerMiddleware: outside the reducer. And if you don't need replay, time travel or DevTools, you don't need Redux: useReducer plus Context gives the same dispatch shape without the store, and Zustand's set merges a partial object rather than requiring a pure reducer, so the replay guarantee simply isn't part of its contract.

Curated: · Written: · Reviewed:

Q&A-7

Walk me through what createSlice and configureStore actually generate, and why a reducer written with mutation syntax still produces immutable state.

Answer

The 90-second answer. Both functions are code generators, not runtime magic. createSlice takes { name, initialState, reducers } and returns an object with the slice's name, a reducer you hand to combineReducers, and an actions map of action creators: one per key in reducers, whose type is `${name}/${reducerKey}`. configureStore is createStore plus wiring: it runs combineReducers over the reducer object you pass, adds the thunk middleware, adds development-only serializableCheck and immutableCheck middleware, and connects the Redux DevTools extension. It returns a normal Redux store, so dispatch / getState / subscribe behave exactly as before.

// @reduxjs/toolkit 2.2, React 18
const todosSlice = createSlice({
  name: 'todos',
  initialState: { items: [], filter: 'all' },
  reducers: {
    todoAdded(state, action) { state.items.push(action.payload); }, // no return, no spread
    filterChanged(state, action) { state.filter = action.payload; },
  },
});

todosSlice.actions.todoAdded.type;        // 'todos/todoAdded'
todosSlice.actions.todoAdded({ id: 1 });  // { type: 'todos/todoAdded', payload: { id: 1 } }
todosSlice.reducer;                       // (state = initialState, action) => nextState

RTK 2.0 also returns slice.selectors with a generated selectSlice, and slice.caseReducers for unit-testing one case directly.

Why mutation syntax works. createSlice builds its reducer with createReducer, which wraps each caseReducers entry in Immer's produce. The state a reducer body receives is a draft, a Proxy over the current state, and the assignment you write is an instruction recorded against the proxy, not a write to the store. When the body returns without a value, Immer replays those instructions onto a shallow copy and returns it.

The important consequence: Immer does not save you copies. Every container you touch is shallow-copied, exactly as {...state, items: [...]} would copy it. What it saves is the bookkeeping, and what it preserves is structural sharing: untouched branches keep their original references, which is what lets useSelector and React.memo bail out.

const before = { items: [{ id: 1, done: false }], filter: 'all' };
const after  = todosSlice.reducer(before, todosSlice.actions.todoAdded({ id: 2 }));

after === before;                   // false
before.items;                       // [{ id: 1, done: false }] — untouched
after.items === before.items;       // false — path copied on write
after.filter === before.filter;     // true  — untouched branch shared
after.items[0] === before.items[0]; // true  — existing item not cloned

What configureStore applies by default. Thunk middleware (so dispatch accepts functions); immutableCheck (redux-immutable-state-invariant), dev only, which throws when an action or previous state was mutated outside Immer; serializableCheck, dev only, which warns on non-serializable values such as Map, Set, Date or class instances in actions or state; DevTools wiring; and getDefaultMiddleware so you can insert your own before or after them. Immer's auto-freeze is on in development and disabled in production builds for performance.

Failure modes.

  1. Mutating state outside a reducer (in a component, selector or thunk) bypasses produce entirely. In dev the frozen state throws Cannot assign to read only property; in production auto-freeze is off, so you corrupt the store and useSelector sees an unchanged reference and renders nothing. Detect: React DevTools Profiler shows no commit for the dispatch while getState() shows the new value.
  2. Returning a value and mutating the draft in the same case makes Immer throw An immer producer returned a new value *and* modified its draft. Pick one style per case.
  3. Non-plain values in state trip serializableCheck and break time-travel debugging: keep Map, Set and class instances out, or normalize to plain objects and arrays.
  4. Sharing a draft outside the reducer leaks the proxy and throws once Immer finalizes it. Anything you store must be a plain value you copied out of the draft.

Do not reach for Immer in a hot path where a reducer is dispatched per animation frame: the proxy bookkeeping is real overhead and a hand-written spread is cheaper. RTK's own escape hatch is createReducer with a prepare callback or plain Redux with hand-written immutability.

Curated: · Written: · Reviewed:

Q&A-9

Why does an inline selector that returns a new object cause a component to re-render on every store update, and how do you fix it?

Answer

The 90-second answer. useSelector compares the selector's return value against the previous one with Object.is by default. A selector that builds an object or array, state => ({ user: state.user, cart: state.cart }), returns a fresh reference on every call, so the comparison never passes and the component re-renders on every store update, including dispatches that never touched its data. Make the returned reference stable: select primitives, pass shallowEqual, or memoize with createSelector.

One correction to the premise. With useSelector this is re-render-on-every-update, not an infinite loop. The literal loop is one layer down, in useSyncExternalStore, which useSelector is built on. React calls getSnapshot during render and again after commit; if it returns a new object each time, React concludes the store changed, re-renders, and throws The result of getSnapshot should be cached to avoid an infinite loop. useSelector avoids that by memoizing the selection against the last snapshot, which is why the symptom is "re-renders too much" rather than a crash.

// react-redux 9.x, React 18
import { useSelector, shallowEqual } from 'react-redux'

// Bad: new object every call, Object.is never passes
const { user, cart } = useSelector(s => ({ user: s.user, cart: s.cart }))

// Good: primitives — reference equality does the work
const user = useSelector(s => s.user)
const cartCount = useSelector(s => s.cart.length)

// Good: one object, shallow compare
const { user, cart } = useSelector(s => ({ user: s.user, cart: s.cart }), shallowEqual)

// Good: memoized, stable output reference (reselect, cache size 1)
const selectSummary = createSelector(
  [s => s.user, s => s.cart],
  (user, cart) => ({ name: user.name, count: cart.length })
)

Trace. Store is { user, cart, todos }; dispatch todos/toggle, which touches only todos.

subscriberselectorresultObject.iscommit
Headers => s.usersame objecttrueno
CartBadges => s.cart.length3 → 3trueno
Summarys => ({ user: s.user, cart: s.cart })new objectfalseyes

Every subscriber's selector still runs on every dispatch: 200 connected components means 200 selector calls per action, and only the comparison decides which ones commit.

Failure modes.

  1. Selector closes over props. useSelector(s => s.items.filter(i => i.id === props.id)) returns a new array each call. shallowEqual rescues this only while the elements are the same object references; s => s.items.map(i => ({ ...i, selected: i.id === props.id })) builds new elements and still fails. Fix: a parameterized memoized selector, or select s.items and derive in useMemo.
  2. shallowEqual is one level. s => ({ user: { ...s.user, active: true } }): the nested object is new, so the shallow compare fails on user. Detect: the dev warning below, or a render counter.
  3. createSelector cache size 1. Two instances calling the same memoized selector with different props thrash the single-entry cache: every call misses, recomputes, and returns a new object. Fix: useMemo(() => createSelector(...), []) per instance, or re-reselect.
  4. Selector cost, not re-render count. Selectors run for every subscriber on every dispatch even when nothing commits. A selector that sorts 10k rows runs 200 times per keystroke.

Detection. react-redux v8+ ships a dev-only check that calls the selector twice with the same state and warns when the two results differ by reference ("Selector unknown returned a different result when called with the same parameters"). In the Profiler, "why did this render" points at the store subscription. Zustand has the same trap; v5's documented fix is useShallow from zustand/react/shallow.

Finally: useSelector only gates the store subscription. A parent re-render still re-renders the child.

Curated: · Written: · Reviewed:

Q&A-10

Where do side effects belong in Redux: thunks, listener middleware, or RTK Query? Walk me through how you choose between them.

Answer

The 90-second answer. Reducers must be pure and synchronous, so every side effect in a Redux app lives outside the store. The decision is which of three layers owns it, and the question that decides it is what the effect is about.

  • Server data: fetch, cache, dedupe, invalidate, poll. Use RTK Query. You declare endpoints and cache tags; it owns the cache, the loading flags and the refetch policy.
  • A one-shot imperative action whose result belongs in the store: submit a form, export a report. Use createAsyncThunk: dispatched from a component or another thunk, it hands you pending/fulfilled/rejected action types.
  • A reaction to actions or state whose dispatch site you don't control: cross-slice coordination, debounced autosave, a websocket, analytics. Use createListenerMiddleware: the effect subscribes to a predicate instead of being called where the action is dispatched.

They compose. A listener can dispatch a thunk or an RTK Query initiate, and RTK Query is implemented on thunks internally.

createAsyncThunkcreateListenerMiddlewareRTK Query
Triggered byyou dispatch itan action matches a predicatea hook mounts, or a tag is invalidated
Owns a cachenonoyes, keyed by endpoint + arg
Dedupemanual, via conditionmanual, via conditionautomatic per cache key
Cancelabort() → signalcancelActiveListeners() + signalautomatic when the last subscriber unmounts
Fitswrites, one-shot flowsdebounce, sockets, cross-slice reactionsreads and writes over HTTP
// Redux Toolkit 2.x, TypeScript 5.x
export const submitOrder = createAsyncThunk(
  'orders/submit',
  async (order: Order, { signal, rejectWithValue }) => {
    const res = await fetch('/api/orders', { method: 'POST', body: JSON.stringify(order), signal });
    if (!res.ok) return rejectWithValue(await res.json());
    return (await res.json()) as Order;
  },
  { condition: (order, { getState }) => !getState().orders.inFlight.includes(order.id) },
);

condition is the reason to prefer createAsyncThunk over a hand-written thunk: a second submit for the same order is dropped before it starts, instead of racing the first.

startAppListening({
  actionCreator: draftChanged,
  effect: async (action, listenerApi) => {
    listenerApi.cancelActiveListeners();   // restart the debounce window
    await listenerApi.delay(800);
    await listenerApi.dispatch(saveDraft.initiate(action.payload));
  },
});

Trace. Keystroke → draftChanged → the listener cancels the previous effect and waits 800 ms → saveDraft.initiate(draft) → PUT /api/drafts/:id → the mutation's invalidatesTags marks {type:'Draft', id} stale → every mounted useGetDraftQuery(id) refetches. Ten keystrokes inside 800 ms produce one request, and the listener, not the component, owns that.

Failure modes.

  1. Thunk last-write-wins. Two requests in flight, the older resolves last, stale data lands. Detect: log start/finish order in the network panel. Fix: condition, or compare a request id in the reducer's fulfilled case.
  2. Fetching from useEffect. useEffect(() => { dispatch(fetchTodos()) }, []) double-fires under StrictMode in dev and never dedupes when two components mount together. RTK Query dedupes by cache key; that is the migration.
  3. Listener leaks. Effects run outside React, so unmounting a component does not stop them. A listener that awaits without cancelActiveListeners() or listenerApi.signal keeps running against a stale argument. Detect: duplicate POSTs after fast navigation.
  4. RTK Query defaults. keepUnusedDataFor is 60 s, refetchOnMountOrArgChange and refetchOnFocus default to false. Forget invalidatesTags and the UI keeps serving the cached copy after a successful write: the bug looks like "the save didn't work".

When not to. A client-only effect with no server and no store write (focus a field, scroll) belongs in the component, not in any of these. And if the app has no server state and no cross-slice reactions, createSlice plus plain thunks are enough; RTK Query buys you a cache you don't have.

Curated: · Written: · Reviewed:

Q&A-11

Walk me through how you'd decide between RTK Query and hand-rolled thunks for server data in a Redux app?

Answer

The 90-second answer. Server data is a cache, not state you own. You don't author it, you don't control its lifecycle, and the copy in the browser is stale the moment it lands. That framing decides the question: if the data comes from an API and more than one component needs it, reach for RTK Query, and hand-roll a thunk only when you can name what RTK Query doesn't give you.

RTK Query is a cache with a request layer on top. createApi generates a reducer, middleware and per-endpoint hooks; the cache key is the serialized query argument, so every component calling useGetUserQuery(42) shares one entry and one in-flight request. An entry is evicted 60 seconds after the last subscriber unsubscribes (keepUnusedDataFor), and mutations invalidate queries by tag rather than by hand.

// @reduxjs/toolkit 2.x
export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  tagTypes: ['User'],
  endpoints: (build) => ({
    getUser: build.query<User, number>({
      query: (id) => `users/${id}`,
      providesTags: (_r, _e, id) => [{ type: 'User', id }],
    }),
    updateUser: build.mutation<User, Partial<User> & { id: number }>({
      query: ({ id, ...patch }) => ({ url: `users/${id}`, method: 'PATCH', body: patch }),
      invalidatesTags: (_r, _e, { id }) => [{ type: 'User', id }],
    }),
  }),
});

The thunk version of the same feature is a slice holding { byId, loading, error }, a createAsyncThunk, and then, because you now own a cache, dedupe, eviction, invalidation and race handling that RTK Query ships.

What you stop writing. Three components on one screen each need user 42. With useEffect(() => { dispatch(fetchUser(42)) }, []) in each, mount fires three GETs; navigating away and back fires three more. With RTK Query, mount fires one request and the other two subscribe to the same cache entry; a remount at t+30s fires zero, and at t+61s fires one because the entry was evicted.

ConcernRTK QueryHand-rolled thunk
Cache keyserialized args, automaticyou invent it
In-flight dedupeper cache keycondition option, or nothing
Eviction60s after last unsubscribenever, unless you write it
Invalidationtagsmanual dispatch
Loading flagsisLoading (first load) vs isFetching (any)one boolean, usually wrong
Normalizationnone: per endpointwhatever you build

Failure modes, and how you catch each.

  1. Treating the RTK Query cache as a normalized store. It isn't: /users/42 and /teams/7/members each hold their own copy of the same user, and patching one leaves the other stale. Detect by rendering the same entity from two endpoints and diffing. Fix with createEntityAdapter in a slice, or by invalidating both tags.
  2. Out-of-order responses in a hand-rolled thunk. The user switches 42 → 43 and the 42 response lands last, overwriting newer data. Detect by throttling to Slow 3G and clicking through the list. Fix with condition to drop stale dispatches, or an AbortController keyed on the id.
  3. isLoading used as the spinner flag. It is true only when there is no data for that cache key, so background refetches show nothing; isFetching is the flag that flips on every request. Detect by watching a refetch leave the UI looking frozen.
  4. Optimistic update without undo. onQueryStarted plus patchResult.undo() in the catch, or the UI keeps a write the server rejected.

When not to use it. WebSocket or streaming data, non-HTTP transports, and fire-and-forget writes where nothing reads the result: a thunk is less machinery. And if the app has no Redux store, RTK Query isn't the tool; TanStack Query is.

Curated: · Written: · Reviewed:

Q&A-14

Your API returns posts with their authors and comments nested in each post. Walk me through how you'd hold that in state, and when normalizing it is overkill?

Answer

The 90-second answer. First ask how the data gets written. Normalize when one entity is referenced from more than one place, or when a node deep in the tree changes on its own: one { byId, allIds } per entity type, relationships held as ids. Leave nested anything written once and rendered as a tree: a form's field objects, a config, a file tree.

The cost that forces the decision is what a nested immutable update actually touches:

// rename the author of one comment, nested state
const next = {
  ...state,
  posts: state.posts.map((p) =>
    p.id !== postId ? p : {
      ...p,
      comments: p.comments.map((c) =>
        c.id !== commentId ? c : { ...c, author: { ...c.author, name } }),
    }),
};

500 posts averaging 20 comments: that walks 500 posts and up to 10,000 comments to change one string, allocates five objects, and changes the identity of state.posts, the post, the comments array and the comment. Every useSelector(s => s.posts) and every memoized child keyed on those objects re-renders. Immer, which RTK's createSlice uses, deletes the spread noise, not the identity churn: the draft still produces new objects along the changed path.

Normalized, the same write is one level deep:

const next = {
  ...state,
  users: {
    ...state.users,
    byId: { ...state.users.byId, [authorId]: { ...state.users.byId[authorId], name } },
  },
};

Only users.byId and that one user change identity. The post header and the comment both read users.byId[authorId], so both update from that single write: no sync effect, no second copy to drift. Redux Toolkit's createEntityAdapter gives you { ids, entities } with memoized selectById/selectAll instead of hand-rolling it.

What you pay: reads become joins. selectPostWithAuthor builds a new object per call, so it has to be memoized (reselect, useShallow) or it re-renders on every unrelated action: the inline-selector trap hiding behind a join. Ordering becomes array work in allIds. And nothing enforces referential integrity: delete a post and its comments, and every id pointing at them is yours to clean up.

Failure modes, and how to catch each.

  1. Two copies drift. The author rendered in the feed header and the author rendered in the comment list are separate objects; one edit leaves the other stale. Detect: a dev-only invariant that walks the state and flags any id appearing twice with differing fields.
  2. Orphans after delete. Ids survive in relationship arrays after the entity is gone, selectors return undefined mid-render, lists render blank rows. Detect: after every action in dev, assert every id in every relationship array exists in the matching byId.
  3. Over-normalized leaves. A six-field address form split into byId costs three dispatched actions per keystroke and buys nothing. Detect: count actions per keystroke; if the reducer tree is larger than the component, back out.
  4. Unmemoized join. Profiler shows commits after actions unrelated to the joined entity: including a no-op dispatch. Detect: same commit count on a no-op.

The trigger is a second reference, or a nested node updated without its parent changing. One reference, one writer, shallow: keep it nested.

Curated: · Written: · Reviewed:

Q&A-12

How does Zustand's subscription model avoid the context re-render problem, and how do selectors work?

Answer

The 90-second answer. A Zustand store is a plain object that lives outside React. create returns a hook, and that hook is a thin wrapper over useSyncExternalStore: it hands React the store's subscribe and getState, plus whatever selector the component passed. There is no provider and no context value, so an update has nothing to propagate down the tree. Each component subscribes on its own, and each subscription carries its own selector. On every set, the store calls every listener; each listener runs its selector and compares the result to the previous one with Object.is. Equal means the hook returns the cached value and React skips that component's render. Unequal means it re-renders: that component only.

Context has no equivalent filter. A new value identity is delivered to every consumer of that context and React re-renders all of them; the only granularity you get is which context you put the value in.

// zustand 5.x, React 18
import { create } from 'zustand'

const useStore = create((set) => ({
  count: 0,
  user: { name: 'ada' },
  inc: () => set((s) => ({ count: s.count + 1 })),
}))

// roughly what create() returns, and what useStore(selector) does
useStore.getState()        // current state, callable anywhere
useStore.setState(partial) // shallow-merges, then notifies every listener
useStore.subscribe(cb)     // cb(state, prevState) -> unsubscribe

function useStore(selector) {
  return useSyncExternalStoreWithSelector(
    useStore.subscribe, useStore.getState, useStore.getInitialState,
    selector, Object.is,   // Object.is is the default
  )
}

useSyncExternalStore is React's; useSyncExternalStoreWithSelector ships in the separate use-sync-external-store package and adds the memoised selection and the equality check.

One set, traced. Store { count: 0, user: { name: 'ada' } }. <Counter/> selects s => s.count, <Name/> selects s => s.user.name, <Static/> uses no hook. inc() runs set, which builds a new state object and calls both listeners:

subscriberselector resultObject.is vs previousoutcome
Counter1falsere-renders
Name'ada'truecached value returned, React bails out
Static——never subscribed, never re-renders

The same update through a context provider holding { count, user } re-renders Counter, Name and Static if all three consume it.

Where the cost moves. Every set runs every subscriber's selector, so a store with 500 subscribers pays 500 function calls per update: cheap individually, not free at 60 Hz. What you buy is that only the components whose slice changed go through React's render and commit. Two failure modes follow. A selector that builds a new object or array each call, s => ({ a: s.a, b: s.b }), fails Object.is every time and re-renders on every store update; useShallow from zustand/react/shallow is the fix, and v5 removed the hook's second equalityFn argument in its favour. And useStore() with no selector returns the whole state, which is exactly the context behaviour you were trying to leave. An inline arrow selector is otherwise fine: the shim re-runs it when its identity changes but still compares the result with Object.is.

Why useSyncExternalStore and not useEffect + useState. Tearing. Under concurrent rendering React can render a tree, get interrupted, and commit later; a store that changed in between would leave two components on screen showing different values. useSyncExternalStore re-checks the snapshot before commit and re-renders synchronously if it moved. It also requires getSnapshot to return a cached value: a fresh object per call is the "getSnapshot should be cached" warning.

When Context is still right. Values that change rarely and are read by many: theme, locale, a router, dependency injection of an API client. Zustand's advantage is per-component granularity plus access from outside React: getState() in an event handler, a test, or a server route. If you need neither, a store is extra machinery.

Curated: · Written: · Reviewed:

Q&A-13

Zustand and Redux Toolkit both hold global state. Walk me through how you'd choose between them for a team: boilerplate, devtools, middleware, bundle size, and who has to live with it.

Answer

The 90-second answer. Ask what the state is and who maintains it. If most of it is server data plus a couple of UI flags, neither library is the answer: that's RTK Query or TanStack Query. For genuine client state, I default to Redux Toolkit when several teams own different slices, when the action log is worth having as an audit trail, or when RTK Query is already in the app. I default to Zustand when the store is small, one or two people maintain it, and I want the store to be a plain module I can import in a route loader or a test without a Provider.

The boilerplate reputation is out of date. RTK 2.x's createSlice generates the action types and creators, so the same todo slice is roughly 25 lines in RTK against 15 in Zustand: a real difference, not 5x.

// zustand 5.x
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';

export const useTodos = create<Store>()(devtools(persist((set) => ({
  items: [], filter: 'all',
  add: (text) => set((s) => ({ items: [...s.items, { id: crypto.randomUUID(), text, done: false }] }), false, 'todos/add'),
  toggle: (id) => set((s) => ({ items: s.items.map(t => t.id === id ? { ...t, done: !t.done } : t) }), false, 'todos/toggle'),
}), { name: 'todos' })));

// @reduxjs/toolkit 2.x
const todos = createSlice({
  name: 'todos',
  initialState: { items: [] as Todo[], filter: 'all' as const },
  reducers: {
    add: { reducer(s, a: PayloadAction<Todo>) { s.items.push(a.payload); },
           prepare(text: string) { return { payload: { id: crypto.randomUUID(), text, done: false } }; } },
    toggle(s, a: PayloadAction<string>) { const t = s.items.find(t => t.id === a.payload); if (t) t.done = !t.done; },
  },
});
export const store = configureStore({ reducer: { todos: todos.reducer } });

Note the prepare callback: crypto.randomUUID() inside the reducer body would make it impure, and the dev-mode immutability check is what catches that.

Zustand 5RTK 2 + react-redux 9
min+gzip (approx.)~1.2 kB~13 kB + ~5 kB
Providernot requiredrequired
DevToolsvia devtools middleware; you name actionson by default; names come from the slice
Middlewarepersist, immer, devtools, subscribeWithSelector, composed by handthunk plus dev-only immutability/serializability checks (2.0 adds an action-creator check); listener middleware, RTK Query
Asyncplain async then setthunk / listener / RTK Query
Structure enforcednoneslices, actions, reducers

Mechanism. Both are the same shape underneath: a store outside React plus a hook over useSyncExternalStore. Zustand's set merges and notifies every subscriber; a component re-renders only if its selector's output fails Object.is. RTK dispatches through the reducer to a new root state and react-redux's useSelector compares the same way. So "Zustand is the only one you can use outside a component" is wrong: useTodos.getState() and store.getState() both work in tests and loaders.

Failure modes. (1) A module-level Zustand store under Next.js App Router is created once per server process, so request A's user can render with request B's state. Detect it by firing two concurrent requests with different session cookies at a route that reads the store; fix it with createStore plus a per-request React context. (2) useTodos(s => ({ a: s.a, b: s.b })) returns a fresh object each call; v5 dropped the custom equality argument, so this re-renders on every update and can loop with "The result of getSnapshot should be cached". Select primitives, or use useShallow from zustand/react/shallow. (3) A Date or Map in RTK state trips serializableCheck in dev: store ISO strings, don't disable the check globally.

Team fit is the real axis. Zustand's freedom means five devs write five store shapes; RTK's cost is the Provider, the wiring, and learning Immer and RTK Query. The failure I'd watch for is a team adopting Zustand to avoid a Provider and then rebuilding Redux badly: unnamed set calls, no devtools middleware, state written from components.

Curated: · Written: · Reviewed:

Q&A-15

A component fetches a user's orders in useEffect and keeps them in useState. Walk me through why that's the wrong tool: what does server state need that client state doesn't?

Answer

The 90-second answer. Split state by who owns the truth, not by where it is used. Client state (a modal's open flag, a filter selection, an unsaved draft) is created in the browser, only this tab can change it, and the copy in memory is authoritative. Server state (the user's orders, the org's members, the invoice) is owned by a system you don't control. The browser holds a cache of it, and that cache is stale the moment it is written: another user, a cron job, or a second tab can change the row and nothing tells you.

That difference creates four requirements client state doesn't have: revalidation (when do I refetch?), deduplication (three components want order 42. One request), a cache lifetime (how long is this copy good enough?), and invalidation on write (I just renamed the org; every cached copy is now wrong).

useState + useEffect gives you none of them. The naive version:

// React 18.2
function Orders({ userId }) {
  const [orders, setOrders] = useState(null);
  useEffect(() => {
    fetch(`/api/users/${userId}/orders`).then(r => r.json()).then(setOrders);
  }, [userId]);
  return orders?.map(o => <Row key={o.id} {...o} />) ?? null;
}

Change userId faster than the network and responses land out of order:

t=0    userId=7  GET /users/7/orders   (slow, 900 ms)
t=50   userId=8  GET /users/8/orders   (fast, 120 ms)  -> renders user 8's orders
t=900  the user-7 response resolves    -> setOrders(user 7's orders) while userId is 8

Be precise about that race, because it is fixable in the effect and it is not the argument against useState. React runs the cleanup before re-running an effect whose dependencies changed, and on unmount, so a flag set in the cleanup drops the stale write:

useEffect(() => {
  let cancelled = false;
  fetch(`/api/users/${userId}/orders`)
    .then(r => r.json())
    .then(data => { if (!cancelled) setOrders(data); });
  return () => { cancelled = true; };
}, [userId]);

AbortController goes further and cancels the request itself, which matters when the response body is large. So the race is a thing you handle, not a thing you escape.

The argument is what's left after you handle it. Mount this component twice, a sidebar badge and a page, and you fire two identical GETs. Navigate away and back and you fire a third, with a loading flash. Nothing refetches when the data changes server-side. Nothing invalidates after a mutation. Every component that fetches re-implements the flag.

Client stateServer state
Source of truththis tab's memorya remote database
Who can change itonly this tabanyone, plus jobs and other tabs
Freshnesscurrent by constructionstale at render time
Lifetimethe sessionneeds a TTL and a revalidation trigger
Duplicatesnot a conceptsame key requested by N components
Write pathsetStatemutation, then invalidate the key

A server-state tool is those four requirements as a library: a keyed cache (['orders', userId]), one in-flight request per key shared by every subscriber, a staleTime after which the entry is refetched in the background, refetch on window focus and reconnect, and invalidateQueries after a mutation. React itself ships no answer here: the managing-state chapter on react.dev is about client state only.

Failure modes, and how you catch each.

  1. Stale after mutation. The user renames a project, the list still shows the old name. Detect: an e2e test that mutates and then asserts the list without a reload.
  2. Duplicate requests. Count GETs per resource in the server access log; a page firing six requests for three resources is the symptom.
  3. A missing cleanup. Throttle to Slow 3G and click through a list quickly; the wrong user's data under the right header means the flag or the abort is absent.
  4. A cache with no expiry on fast-moving data. A dashboard showing yesterday's numbers at 09:00 because nothing ever refetched.

The other direction. Don't dump server data into a global client store as the primary copy: you have then hand-written a cache and own its invalidation. RTK Query is the same idea living inside Redux. And a form draft is a hybrid: client state until submit, server state after.

Curated: · Written: · Reviewed:

Q&A-16

Walk me through staleTime versus gcTime in TanStack Query, what actually makes a query stale, and what triggers a refetch?

Answer

The 90-second answer. "Stale" does not mean wrong or expired. It means eligible for a background refetch. staleTime is the window after a successful fetch during which the cache answers without touching the network; gcTime is a separate clock that starts when the last component observing a query unmounts, and it controls how long that entry stays in memory. They are independent: one governs freshness, the other governs retention. TanStack Query v5 defaults are staleTime: 0 and gcTime: 5 * 60 * 1000.

OptionClock startsDefault (v5)At expiry
staleTimea successful fetch0 msdata becomes stale; the next trigger refetches in the background
gcTimethe last observer unmounts300000 msthe cache entry is deleted; the next mount is a cold load
// @tanstack/react-query v5
useQuery({
  queryKey: ['invoice', id],
  queryFn: () => fetchInvoice(id),
  staleTime: 30_000,    // 30s where we don't ask again
  gcTime: 5 * 60_000,   // keep the entry 5 min after the last component unmounts
});

What triggers a refetch. Mount (refetchOnMount, default true), window focus (refetchOnWindowFocus, default true), reconnect (refetchOnReconnect, default true), refetchInterval, and invalidateQueries from a mutation. The first three are gated on staleness: fresh data short-circuits them. invalidateQueries and refetchOnMount: 'always' are not gated; they refetch regardless. The queryKey is the cache identity, so two components with the same key share one entry and one in-flight request.

A trace. User opens the invoice list at t=0; the fetch resolves at t=0.4s. They navigate away at t=2s, so the observer count hits zero and the gcTime clock starts. They come back at t=20s: cache hit, data is stale (staleTime: 0), so it renders instantly from cache and revalidates in the background. They come back at t=6min: the entry was collected at t=5min, so isPending is true and they see a spinner. That instant-render-plus-background-refresh is the whole point: stale-while-revalidate.

Failure modes.

  1. gcTime < staleTime. The entry is deleted before it can ever be served fresh, so every remount is a cold load. Keep gcTime >= staleTime.
  2. staleTime: Infinity with no invalidation. Nothing ever refetches and the UI is frozen at first load. Pair it with invalidateQueries in the mutations that change that data.
  3. Treating stale as invalid. With staleTime: 0, rendering a spinner on isFetching makes every focus event flash a loading state. Use isPending for the first load, isFetching for background activity.
  4. gcTime: 0. Data is dropped the moment the last observer unmounts, so back-navigation is always a cold load.

Choosing values. Reference data that changes weekly (currencies, plan tiers) can take staleTime: 5 * 60_000 or Infinity with invalidation. A dashboard that must be current on focus takes the default 0. Anything user-specific and mutable (a cart, a draft) wants a short staleTime plus explicit invalidation after the write.

Curated: · Written: · Reviewed:

Q&A-17

Walk me through an optimistic update end to end: what you write before the request goes out, what you roll back when it fails, and what you invalidate afterwards?

Answer

The 90-second answer. An optimistic update writes the expected result into the cache before the server confirms it, so the UI settles in one frame instead of one round trip. You trade a small chance of showing a lie for 100–300 ms of perceived latency saved on every write. The lie is only acceptable if three things are designed rather than improvised: the snapshot you roll back to, the scope of that rollback, and what you invalidate afterwards so the cache converges on the server's truth.

Scope is where implementations break. Snapshot the row you touched, not the whole list: a whole-list snapshot throws away every other mutation that landed while the failed request was in flight.

// React 18.2, plain hooks — the same shape TanStack Query's onMutate/onError encodes
function useToggleTodo(todos, setTodos) {
  const latest = useRef(todos);
  useEffect(() => { latest.current = todos; }, [todos]);   // read state outside the updater

  return useCallback(async (id) => {
    const before = latest.current.find(t => t.id === id);          // 1. snapshot one row
    if (!before) return;

    setTodos(prev => prev.map(t => t.id === id ? { ...t, done: !t.done } : t));  // 2. optimistic

    try {
      const saved = await api.patch(`/todos/${id}`, { done: !before.done });     // 3. confirm
      setTodos(prev => prev.map(t => t.id === id ? saved : t));                  //    server wins
    } catch (err) {
      setTodos(prev => prev.map(t => t.id === id ? before : t));                 // 4. scoped rollback
      throw err;
    }
  }, [setTodos]);
}

Why the scope matters. Two rows, both done: false. The user toggles 7, then 9, before either response returns.

teventclient 7client 9server 7server 9
0—falsefalsefalsefalse
1toggle(7), PATCH A senttruefalsefalsefalse
2toggle(9), PATCH B senttruetruefalsefalse
3A returns 500falsetruefalsefalse
4B returns 200falsetruefalsetrue

With a whole-list snapshot taken at t1, step 3 restores row 9 to false as well. If B's success handler only patches row 9 from its response, the flicker is cosmetic; if B is fire-and-forget, the client shows false while the server holds true and stays wrong until the next refetch. Scoped rollback makes step 3 touch exactly one row.

Invalidation. Decide per mutation whether to write the response into the cache or mark keys stale:

MutationActionReason
toggle rowinvalidate ['todos'] prefixserver may reorder or recompute counts
createinvalidate ['todos'], seed ['todo', newId]id and defaults come from the server
deleteinvalidate ['todos'], remove ['todo', id]a detail key must be dropped, not refetched

Write the response directly (setQueryData) when the endpoint returns the full updated entity and nothing else changed; invalidate when the response is partial or the write affects siblings.

Failure modes, and how you catch each.

  1. Refetch racing the optimistic write. A refetch started before the mutation lands after it and overwrites the optimistic value with pre-mutation data. Cancel in-flight queries for the key before writing (cancelQueries in TanStack Query's onMutate). Detect: the row flips back for one frame, then forward again.
  2. Out-of-order responses on one row. Two PATCHes, the older resolves last and wins. Detect: a row that ends in the opposite state from the last click. Fix: disable the control while pending, or carry a per-row sequence number and drop stale responses.
  3. Rollback lost on unmount. The component that owned the snapshot is gone, so the setter is a no-op and the cache keeps the lie. Keep mutation state in the store or query cache, not in component state.

React 19's useOptimistic removes the manual snapshot: the optimistic value lives only for the duration of the action and reverts when it settles, but it does not solve overlapping writes to the same row or the invalidation question.

Curated: · Written: · Reviewed:

Q&A-18

A teammate stores `filteredItems` in state and updates it inside a `useEffect` whenever `items` or `query` changes. Walk me through why that is a bug and what you would do instead.

Answer

The 90-second answer. Derived state is not state. If a value can be computed from props or existing state, compute it during render. Storing it in state and syncing it in an effect creates a second source of truth, and the effect runs after the browser has already painted, so the first render after query changes shows the previous filtered list. Then setFiltered schedules a second render. You get a stale frame, an extra commit, and a class of bugs that only appear when the effect's dependency list is wrong.

// React 18 — the bug
function SearchList({ items, query }) {
  const [filtered, setFiltered] = useState(items);
  useEffect(() => {
    setFiltered(items.filter(i => i.name.includes(query)));
  }, [items, query]);
  return <List data={filtered} />;
}

Trace: query goes from '' to 're'. Render 1 runs with filtered still holding all items; React commits and paints the full list. The effect then runs, calls setFiltered, and render 2 paints the filtered list. The user sees the old list for one frame. If items is a new array on every parent render and the effect sets a new array every time, the dependency items changes again and you loop.

The fix is to delete the state and the effect:

function SearchList({ items, query }) {
  const filtered = items.filter(i => i.name.includes(query));
  return <List data={filtered} />;
}

If the filter is measurably expensive, wrap it in useMemo with the same dependencies: that is a performance tool, not a correctness one. React may still throw the memo away, so the code must be correct without it.

When an effect is the right tool. Effects are for synchronizing with something outside React: a WebSocket subscription, a DOM measurement, an analytics call. They are not for copying props into state. The one legitimate "state reset on prop change" case is better handled by key: <Profile key={userId} user={user} /> remounts the component and resets all its state without an effect. If you truly need to adjust state during render, React's own pattern is to store the previous prop and compare it in the render body, not in an effect.

Failure modes to name. (1) Stale paint: the UI shows the old derived value for one commit; detect it in the Profiler as two commits per keystroke. (2) Infinite loop: the effect sets a new object or array every run and that value is in its own dependency list. (3) Lost user edits: the effect overwrites local edits whenever the source changes. (4) SSR mismatch: effects do not run on the server, so the server HTML and the first client render disagree. (5) Dependency drift: an omitted dependency leaves the derived value permanently stale, and nothing throws.

The rule to say out loud. Keep the minimal source state (items, query) and derive everything else during render. If you cannot derive it, it is source state; if you can, it is not state at all.

Curated: · Written: · Reviewed:

Q&A-19

Your team keeps every form field in the Redux store so "anything might need it." When is that the wrong call, and where should that state live instead?

Answer

The 90-second answer. A form draft is created by one screen, read by that screen, and changes on every keystroke. Global state is the opposite on all three counts, so the draft belongs where it is used: useState/useReducer inside the form for a handful of fields, uncontrolled inputs read as FormData at submit when the form is mostly text, and a form library once per-field validation and re-render isolation start to matter. The store keeps what outlives the form (the submitted entity in a query cache, session, feature flags) plus a narrow persisted draft slice, and only if the product genuinely needs "close the tab, come back later."

Why the store is the wrong unit for keystrokes. A global store is a broadcast: every dispatch notifies every subscriber whose selected value changed. A controlled input dispatches on each character, so typing a 60-character message is 60 actions, 60 Immer produce calls, and a re-render of every component selecting that slice. None of the reasons you wanted global state (shared access, persistence, time travel) are useful for a half-typed email address. Redux DevTools turns into a log of individual letters, and time-travelling to the middle of a word tells you nothing.

Worked example, illustrative: a 30-field checkout form with 12 components selecting state.form, filled by hand in ~40 keystrokes, produces 40 actions, 40 Immer drafts and roughly 480 component renders. For state discarded at submit. Measure it in your own Profiler by counting commits per keystroke; that count is the argument.

Where each piece goes.

DataLifetimeHome
Field values being typedseconds, one form instanceuseState/refs inside the form component
Errors, touched flagsone form instancesame component, or the form library
Submitted entityuntil invalidated/refetchedquery cache (TanStack Query, RTK Query)
Session, theme, feature flagsapp lifetimecontext or store
Draft that must survive reloadminutes to daysstore slice + persist, written on step boundary or blur

What to write instead. React 19 lets the DOM hold the value and hands you a FormData at submit:

// React 19.1 + React DOM. No field state in any store.
function SignupForm() {
  const [error, submit, isPending] = useActionState(async (_prev, formData) => {
    const res = await api.signup(Object.fromEntries(formData));
    return res.ok ? null : { message: res.error };
  }, null);

  return (
    <form action={submit}>
      <input name="email" type="email" required />
      <input name="password" type="password" minLength={12} required />
      <button disabled={isPending}>Create account</button>
      {error && <p role="alert">{error.message}</p>}
    </form>
  );
}

Nothing re-renders while typing, the pending state comes from the action rather than a store flag, and validation errors live in the component that displays them. If you need controlled fields, keep them controlled locally: the form re-renders, the app doesn't.

Failure modes, and how you catch each.

  1. Two instances colliding. state.form.email is a singleton, so opening the same form in a modal while the page form is half-filled means both write the same fields and the second silently takes over. Detect: render two instances in a test and assert independent drafts.
  2. The draft outliving the screen. Navigate away mid-form, come back, and the previous values (or the previous user's, on a shared machine) are still there. Detect: assert the slice is cleared on unmount.
  3. Persisted drafts leaking PII. A persist middleware over the whole store writes a half-typed password or card number to localStorage. Detect: type in the form, then read localStorage.
  4. Validation that fires a request per keystroke. A username-availability check under keystroke dispatch returns out of order, and the last response to land is not the last value typed. Detect: throttle to 3G in DevTools and type fast; the verdict flickers.

When global is right anyway. A multi-step wizard that survives navigation and reload, a collaborative editor where two people share a draft, save-as-draft. Even then hold committed step values, not every keystroke. If one component tree reads it and it dies at submit, it isn't global state: it's component state with extra steps.

Curated: · Written: · Reviewed:

Q&A-20

A product list has a search box, category filters, a sort order and pagination. Walk me through which of those belong in the URL rather than component state, and what breaks when you get it wrong?

Answer

The 90-second answer. The test isn't "is this state?" but "would a user want to send this view to someone else?" Filters, tabs, sort order, pagination and search terms describe what is being looked at, not what the app is doing. They belong in the URL, which makes them shareable, bookmarkable, reload-safe and reachable with the back button. Modal open/closed, hover, an unsaved draft, a drag offset: those stay in React state, because nobody wants a link to your half-typed comment.

The mechanism: the URL is the single source of truth and React derives from it. Never mirror it into useState and sync with an effect.

// React Router 6.22 / Next.js App Router
function useFilters() {
  const [params, setParams] = useSearchParams();
  const filters = {
    q: params.get('q') ?? '',
    category: params.get('category') ?? 'all',
    sort: params.get('sort') ?? 'newest',
    page: Number(params.get('page') ?? 1),
  };
  const setFilters = (patch, { replace = false } = {}) => {
    const next = new URLSearchParams(params);
    for (const [k, v] of Object.entries(patch)) {
      if (v === '' || v == null || v === DEFAULTS[k]) next.delete(k);
      else next.set(k, String(v));
    }
    setParams(next, { replace });   // replace: no history entry
  };
  return [filters, setFilters];
}

Two details carry most of the weight. Defaults are deleted from the URL rather than written, so ?page=1&sort=newest and /products are the same page: one cache key, one shareable link. And replace is what stops a search box from pushing a history entry per keystroke: type "laptop" with push and the user needs six back presses to leave the page.

Where each kind of state lives.

StateHomeWhy
search term, filters, sort, pageURLshareable, back button, reload-safe
selected tab in a detail viewURL (often)deep-linkable; a tab is a view
modal open, hover, focusReact statetransient, nobody links to it
form draft before submitReact stateURL history would leak half-typed input
drag position, scroll offsetref / React statetoo high-frequency; history spam
auth token, PIIneither in the URLURLs land in logs, analytics and Referer

Failure modes. The classic one is two-way sync: one useEffect writes state to the URL, another reads the URL into state. The back button then fires the effect, which rewrites the URL, and you get a render loop or a history entry the user can't escape. Detect it by watching history length in DevTools while clicking back once.

Second: the URL becomes the query key. If you fetch with TanStack Query keyed on searchParams, a non-canonical URL (?page=1 versus no page) is a cache miss for identical data. Canonicalise on write.

Third: hydration. Reading window.location during render breaks SSR; useSearchParams is the supported path, and in the Next.js App Router a component that reads it must sit under a Suspense boundary or the route opts into client rendering.

Fourth: length and encoding. Practical URL limits are around 2,000 characters before proxies and older servers start truncating, so a 500-ID selection does not go in the query string: it goes in a POST body or in server-side state keyed by an opaque id.

When not to. If the state changes faster than a human navigates, or is meaningless outside the current session, the URL is the wrong home. And if nobody on the team owns routing, a URL-driven page is harder to test than a useState one: a real cost, not a style preference.

Curated: · Written: · Reviewed:

Q&A-21

Your component tracks isLoading, isError, and hasData as three separate booleans. Walk me through when that stops scaling and what you replace it with.

Answer

The 90-second answer. Count the flags. Three booleans give eight combinations and usually three of them are legal: the other five are states your UI can render but shouldn't. The moment you write if (isLoading && !isError), or set three flags inside one handler, you don't have three pieces of state, you have one state variable spelled as three, and nothing tells you when they disagree. The fix is to make the state a single value from a closed set, 'idle' | 'loading' | 'success' | 'error', and move every transition into one function. useReducer does that. A state machine does that plus one more thing: it records which events are legal in which state, so an event arriving at the wrong time is a no-op instead of a branch you have to remember to write.

// React 18 — three flags, eight reachable combinations
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError]     = useState(false);
const [data, setData]           = useState(null);
// one field, four reachable values
const initialState = { status: 'idle', data: null, error: null };

function reducer(state, action) {
  switch (action.type) {
    case 'FETCH':   return { status: 'loading', data: null, error: null };
    case 'RESOLVE': return { status: 'success', data: action.data, error: null };
    case 'REJECT':  return { status: 'error', data: null, error: action.error };
    default:        return state;
  }
}

Every transition resets data and error, so status: 'success' carrying a stale error is unrepresentable. With flags that reset is three separate setX calls in each handler; React 18 batches them, so forgetting one is a silent bug rather than a crash.

Where the reducer stops. The switch has no memory of which state it is in. Dispatch RESOLVE while idle and it moves to success. If your domain has events that are only meaningful in some states (a CANCEL that applies only while loading, a SUBMIT to ignore while saving) you are back to hand-written guards. That is where a transition table or a machine (XState) earns its dependency:

const transitions = {
  idle:    { FETCH: 'loading' },
  loading: { RESOLVE: 'success', REJECT: 'error', CANCEL: 'idle' },
  success: { FETCH: 'loading' },
  error:   { FETCH: 'loading' },
};
// dispatch('CANCEL') in 'success' matches nothing → state unchanged

The table is data, so you can loop over every (state, event) pair in a test, and XState's visualizer reads the same structure.

Failure modes.

  1. Out-of-order responses. Type "ab": request A for "a" and B for "ab" are in flight, A resolves last, and the flags version renders "a"'s results under "ab". Detect: log the request id with each resolve, if the rendered data's id isn't the latest issued, you lost the race. Fix: abort the previous request, or carry a request id in state and ignore a resolve whose id isn't current. The machine version makes that a guard on the RESOLVE transition.
  2. Double submit. isSaving is set in the click handler, but the button reads it one render later, so two clicks in the same tick both pass the check. Detect: two POSTs with the same idempotency key in the network log. Fix: disable on the transition, not on the flag, and make the server idempotent.
  3. Stale closure. An async callback reads isLoading from the render that created it. With a reducer, dispatch is stable and the reducer sees current state, so that class of bug disappears.

When not to. One boolean for one modal is fine. Two flags that never interact are fine. The signal is coupling, not count: if a handler sets more than one flag, or a render branch reads two together, collapse them. And don't reach for XState for a fetch: a status union plus a reducer covers it. Machines pay off when legal transitions are few relative to events, and when states have entry/exit behaviour (timers, subscriptions) that must start and stop with them.

Curated: · Written: · Reviewed:

Q&A-22

Your Next.js App Router app keeps a Zustand store in a module-level singleton and persists it to localStorage. Walk me through what breaks on the server, and how you'd fix per-request instances, rehydration, and the server/client boundary.

Answer

The short answer. Three failures, and they're independent. A store created at module scope is a singleton for the life of the Node process, so request B can render with request A's state. localStorage doesn't exist on the server, so a store that reads it during the first render produces HTML the client can't match. A Server Component has no hooks and no context, so it can't read a client store at all. Anything it needs has to arrive as serializable props.

FailureSymptomFix
Module-level storeUser B renders user A's cartVanilla store factory, one instance per provider mount
localStorage read during renderHydration mismatch (React error #418), subtree re-rendered on the clientskipHydration: true and rehydrate() in an effect
Store read from a Server ComponentNo hooks availablePass plain data across the boundary as props

Per-request instances. Zustand's create returns a hook bound to one module-level store, so it leaks across requests. Use the vanilla createStore instead, and give each provider its own instance.

// lib/cart-store.ts
import { createStore } from 'zustand/vanilla';
import { persist, createJSONStorage } from 'zustand/middleware';

export type CartState = { items: string[]; add: (id: string) => void };

export const makeCartStore = () => createStore<CartState>()(persist(
  (set) => ({ items: [], add: (id) => set((s) => ({ items: [...s.items, id] })) }),
  {
    name: 'cart',
    storage: createJSONStorage(() => localStorage),
    skipHydration: true,
    version: 2,
    migrate: (persisted, from) => (from < 2 ? { ...(persisted as object), items: [] } : persisted),
    partialize: (s) => ({ items: s.items }),
  },
));
// app/cart-provider.tsx
'use client';
import { createContext, useContext, useEffect, useRef, type ReactNode } from 'react';
import { useStore } from 'zustand';
import { makeCartStore, type CartState } from '@/lib/cart-store';

type CartStore = ReturnType<typeof makeCartStore>;
const CartContext = createContext<CartStore | null>(null);

export function CartProvider({ children }: { children: ReactNode }) {
  const ref = useRef<CartStore | null>(null);
  if (!ref.current) ref.current = makeCartStore();
  useEffect(() => { ref.current?.persist.rehydrate(); }, []);
  return <CartContext.Provider value={ref.current}>{children}</CartContext.Provider>;
}

export function useCart<T>(selector: (s: CartState) => T): T {
  const store = useContext(CartContext);
  if (!store) throw new Error('useCart called outside CartProvider');
  return useStore(store, selector);
}

The initializer runs once per component instance. On the server each request renders a fresh tree, so each request gets its own store. On the client it runs once per mount. app/layout.tsx stays a Server Component and renders <CartProvider>. If the store needs server data, extend the factory to take an initial state, for example makeCartStore(initialItems), and have a Server Component fetch that data and pass it as a prop to a client wrapper.

Rehydration. With skipHydration: true, persist leaves storage alone during the first render, so the server HTML and the client's first render both show items: []. Hydration matches. The effect then calls rehydrate(), the persisted cart loads, and React commits a second render. If you read localStorage during render instead, the client output differs from the server HTML, React reports the mismatch (#418 in production builds), and it discards the server markup for that subtree.

createJSONStorage catches errors from its getter, so creating the store on the server doesn't throw when localStorage is missing. Only rehydrate() touches storage, and it runs in an effect, which never runs on the server.

Failure modes.

  1. Cross-request leak. Two users' carts mix. Detect it with two concurrent requests carrying different session cookies and a diff of the HTML. Sequential requests can pass even with a singleton store.
  2. Stale persisted shape. A deploy adds a field, the old JSON lacks it, and selectors read undefined. Bump version and handle the old shape in migrate. Test by seeding localStorage with the previous version's JSON.
  3. Auth flash. A persisted token rehydrates after first paint, so protected UI renders logged-out for a frame. Detect it by throttling CPU and watching the first paint. Gate protected UI on a hydrated flag, or keep the token in a cookie the server can read.
  4. Non-serializable seed data. A Map or a function passed across the server/client boundary fails at build time. Pass arrays and plain objects only.

Curated: · Written: · Reviewed:

Q&A-23

Walk me through how you'd test a component that reads from a global store: what belongs in a store-level test, what belongs in a component test, and which assertions you'd avoid?

Answer

The 90-second answer. Split by what the test can see. A reducer, a Zustand store's actions, a selector: those are plain functions over plain data, so test them directly: feed an action, assert the next state. A component's job is to wire that state to the screen, so test it through the UI with a real store and assert on what the user sees. The line that matters is the assertion, not the layer: assert on outputs (next state, rendered text), never on how the component got there (which action was dispatched, what the state object looked like halfway through).

// cartSlice.ts — Redux Toolkit 2.x
const cartSlice = createSlice({
  name: 'cart',
  initialState: { items: [] as Item[], coupon: null as string | null },
  reducers: {
    itemAdded(state, action: PayloadAction<Item>) { state.items.push(action.payload) },
  },
})

// store-level: pure function, no React, no provider, ~1 ms
it('appends the item', () => {
  const next = cartSlice.reducer(undefined, cartSlice.actions.itemAdded({ sku: 'A1', qty: 2 }))
  expect(next.items).toEqual([{ sku: 'A1', qty: 2 }])
})
// component-level: real store, real reducers, network mocked at the edge (MSW)
it('shows the item after the user adds it', async () => {
  const store = makeStore()
  render(<Provider store={store}><ProductPage sku="A1" /></Provider>)
  await userEvent.click(screen.getByRole('button', { name: /add to cart/i }))
  expect(await screen.findByText('A1')).toBeInTheDocument()
})

The version of that second test people actually write is the one to avoid:

const dispatch = vi.fn()
vi.mock('./store', () => ({ useAppDispatch: () => dispatch }))
// ...
expect(dispatch).toHaveBeenCalledWith({ type: 'cart/itemAdded', payload: { sku: 'A1', qty: 2 } })

Delete the itemAdded reducer and this test still passes. It asserts that the component called a function with a string, which is true whether or not the cart works.

What each assertion couples you to.

AssertionCoupled toSurvives a refactor?Catches a broken cart?
dispatch called with { type: 'cart/itemAdded' }component internalsnono
store.getState() deep-equals a fixturethe whole state shapeno: any new field fails ityes
reducer output for one actionthe reducer's contractyesyes
rendered text after a clickuser-visible behaviouryesyes

Where the coupling is legitimate. An action type stops being private the moment something outside the slice depends on it: another slice's extraReducers, a redux-persist migration, listener middleware, a devtools time-travel workflow you actually use. Then asserting on it is asserting on a contract, and it belongs in a store-level test that dispatches the action and checks both slices, not in a component test that spies on dispatch.

Zustand is easier here because the store is a plain object with getState/setState/subscribe outside React (Zustand 4.4 added getInitialState):

beforeEach(() => useCart.setState(useCart.getInitialState(), true))
it('adds an item', () => {
  useCart.getState().add({ sku: 'A1', qty: 2 })
  expect(useCart.getState().items).toHaveLength(1)
})

No renderer, no provider, no act. The component test then only has to prove the component reads the store.

Failure modes. A suite that mocks the store or the selector passes with the feature deleted: detect it by mutation testing, or by deleting one reducer case and checking the suite goes red. A toMatchSnapshot() on the whole store fails on every unrelated field, so people update it without reading it. Asserting on render counts or useEffect call counts locks in the current hook layout. And a component test per reducer case is the wrong shape: 40 cases at ~50 ms of jsdom each is two seconds of suite time for something the reducer test covers in 40 ms.

Curated: · Written: · Reviewed:

Q&A-24

A teammate says context re-renders the whole app and wants to move to Zustand. Walk me through measuring the real cost with the Profiler, and where useSyncExternalStore fits.

Answer

The 90-second answer. "Context re-renders everything" is two claims and both are usually false as stated. Context re-renders exactly the components that call useContext on that context, not the provider's children, not the rest of the tree. And a re-render is not a DOM write: React renders, diffs, and commits only if the output changed. So profile before migrating. If the flamegraph shows 200 consumers of a context whose value changes 10×/s, that's 2,000 renders/s and worth fixing. If it shows three, a store migration buys nothing.

What the Profiler tells you. React DevTools → Profiler → gear icon → "Record why each component rendered while profiling". Record one interaction. The flamegraph gives per-commit render time, the ranked chart sorts by self time, and clicking a component names the reason: props changed, parent re-rendered, context changed, hooks changed. That distinction is the whole argument: "parent re-rendered" is a memo or children problem, not a context problem. Profile a production build: StrictMode double-invokes render in dev, so dev numbers are roughly 2× and the extra renders never commit.

The mechanism. When a provider's value fails Object.is against the previous one, React walks the fiber tree and marks every fiber holding a matching useContext dependency. It does not descend into non-consumers. Cost is consumers × cost of each consumer's render, paid whenever the value's identity changes: including when the provider re-renders for an unrelated reason and the value is an inline literal.

// React 18+ — new object every provider render, so every consumer re-renders
<Ctx.Provider value={{ user, setUser }}>

Fix ladder, cheapest first: useMemo the value on its real deps; split state and dispatch contexts (helps only consumers that need one half); pass the subtree as children so the provider's own re-render doesn't reach it; colocate the state lower; only then an external store.

Where useSyncExternalStore fits. It subscribes a component to a store outside React and reads a snapshot.

// React 18+
function createStore(initial) {
  let state = initial;
  const listeners = new Set();
  return {
    getState: () => state,
    setState: (patch) => { state = { ...state, ...patch }; listeners.forEach(l => l()); },
    subscribe: (l) => { listeners.add(l); return () => listeners.delete(l); },
  };
}

const count = useSyncExternalStore(store.subscribe, () => store.getState().count);

React compares consecutive snapshots with Object.is and schedules a re-render on change. It re-reads getSnapshot during render and, if the value moved, re-renders synchronously instead of committing a torn UI: that is the concurrent-rendering reason it exists. The trap: getSnapshot must return a cached value. () => ({ count: store.getState().count }) allocates on every call, React sees a change on every check, and you get "The result of getSnapshot should be cached to avoid an infinite loop". Select primitives, or use useSyncExternalStoreWithSelector / Zustand's useShallow.

The payoff is subscription granularity: a component selecting count re-renders when count changes, not when any other field does. Context can't do that without one context per field.

Failure modes. Memoizing the context value with a wrong dep list stops consumers updating entirely: the value never changes identity, so nothing re-renders; catch it with a test asserting the consumer shows new data. A shallow-equality selector that ignores a nested field hides real updates. And a Profiler session full of renders with no commits means the renders are cheap; leave them alone.

Curated: · Written: · Reviewed:

Q&A-25

You have 180 components reading from a Redux store and the team wants Zustand. Walk me through migrating incrementally without a big-bang rewrite, and what you'd tell a team picking a library from scratch today?

Answer

The 90-second answer. Redux and Zustand are both external stores that React reads through useSyncExternalStore; the difference lives at the call site, not in the data. So the migration unit is one slice plus the components that read it: never the app. Two invariants make that safe: exactly one writer per slice at any moment, and an adapter hook in front of every read so component code never changes. Move slices in dependency order, leaf-first. A team picking today should pick on exit cost, not on features: which seam do you leave behind if you change your mind in eighteen months?

// React 18, TypeScript 5. Components import this, never the store.
// Phase 1 — Redux underneath.
export function useCart() {
  const items = useSelector(selectCartItems);      // react-redux 9
  const dispatch = useDispatch();
  return { items, add: (id: string) => dispatch(cartActions.add(id)) };
}

// Phase 2 — Zustand underneath. Same signature, zero component edits.
export function useCart() {
  const items = useCartStore((s) => s.items);      // zustand 4
  const add = useCartStore((s) => s.add);
  return { items, add };
}

The signature is the contract. If useCart builds a fresh object every render you have reintroduced the selector-identity bug from the other direction: return the store's own action references, or memoize.

Order and arithmetic. Twelve slices, 180 components, team of four. Sort by fan-in: ui (theme, modals), cart, filters first; session and entities last, because everything derives from them. One slice per PR: add the new store, flip the adapter, delete the old slice, run the suite. Two slices per sprint is realistic, so roughly six sprints, and the app ships after every one.

Failure modes, and how you catch each.

  1. Dual-write divergence. Mirroring a slice into both stores "for safety" drifts the first time a write path misses one copy. Detect: a dev-only assertion that compares both stores on every render, or don't do it.
  2. Middleware that doesn't port. redux-persist rehydration, RTK Query's cache and redux-observable epics have no drop-in equivalent. Persist becomes zustand/middleware's persist; RTK Query stays where it is, because it is a server cache, not client state; epics become listener middleware or plain async functions. Inventory middleware before you promise a date.
  3. Lost replay. Redux DevTools gives an action log you can replay; Zustand's devtools middleware gives state diffs, not replayable actions. If "replay the action log" is how you debug, that is a real cost.
  4. Tests that mock the store. jest.mock('react-redux') breaks the moment the adapter flips. Render through the adapter instead.

Choosing today: ask about exit cost.

ChoiceSeam you leave behindCost to leave later
Zustandone hook per slicelow: swap the hook body
Redux Toolkitactions + selectorsmedium: actions port, middleware doesn't
Jotai / atomsatom keysmedium: atoms leak into component code
Context + useReducerprovider + dispatchlow mechanically, high if state and dispatch were never split

Bundle size is the weakest argument: roughly 1 kB min+gzip for Zustand against ~13 kB for @reduxjs/toolkit plus react-redux. Real, but noise next to one hero image. Check the versions you pin rather than trusting a blog. The strongest argument is the seam: a library you can leave in one PR per slice is a library you can afford to be wrong about.

Curated: · Written: · Reviewed: