Skip to the page

State: snapshots, updates and where state lives · core

Shaping state: lifting up, derived values and immutable updates

Keep the minimum state, compute everything else during render, lift shared state to the closest common parent, and always replace objects and arrays instead of mutating them so Object.is can see the change.

The notes

What you must know

  • Single source of truth: if two components need the same value, lift it to their closest common parent and pass it down with an onChange callback.
  • Do not store what you can calculate. fullName from first and last, or a filtered list from items and query, is computed in render (wrap in useMemo only if it is truly expensive).
  • Avoid duplicated state: store selectedId, not a copy of the selected object, so edits to the list cannot go out of sync.
  • Never mutate state. items.push(x); setItems(items) passes the same array, Object.is says "no change", and React may skip the update. Use setItems([...items, x]).
  • Nested updates copy every level on the path: { ...user, address: { ...user.address, city } }. Unchanged branches keep the same reference, which lets memoized children skip work.
  • Immer (used by Redux Toolkit) lets you write "mutating" code on a draft and produces an immutable copy for you.
  • Group related values that always change together (form fields) in one object or a reducer; avoid contradictory booleans like isLoading + isError both true; prefer a single status field.

The red pen

Common traps: mistake → fix

  • Mistake: "Mirror props into state with an effect"

    Fix: compute from props in render, or use a key to reset.

  • Mistake: "setUser(user) after user.name = x updates the screen"

    Fix: same reference, so React can bail out; copy the object.

  • Mistake: "Spread makes a deep copy"

    Fix: spread copies one level only.

Easy to hard

Questions interviewers ask, easy to hard

  1. Two sibling components need the same value. Where should that state live?
  2. Why should you not store fullName in state?
  3. Why is mutating an object in state and then calling the setter a bug?
  4. Update the city inside user.address without mutation. Which references change and which stay the same?

Your first interview is free

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

Start your free interview