SkillPilotAI

Objects and arrays in state

When state is an object or an array, React decides whether to re-render by comparing references, not contents. So state must be updated immutably (a new copy every time), derived values should be calculated rather than stored, and shared state belongs in the closest common parent.

27.1 The problem: we modified the object

  • Profile's state is { name: "Asha", city: "Pune" }.
  • moveToDelhi sets user.city = "Delhi" directly and passes the same object to setUser.
  • No matter how many clicks, the screen still shows Asha: Pune.
React (JSX)
function Profile() {  const [user, setUser] = useState(    { name: "Asha", city: "Pune" }  );  function moveToDelhi() {    user.city = "Delhi";    setUser(user);  }   return (    <button onClick={moveToDelhi}>      {user.name}: {user.city}    </button>  );}
Output
-- before click --[button] Asha: Pune-- after click --[button] Asha: Pune

27.2 Why didn't the screen update?

  • The setter compares the new value with the old one using the reference (Object.is), not the properties inside.
  • Like a courier who only checks the tracking number and never opens the parcel.
  • We mutated and handed back the same object, so old === new and React skips the re-render.
  • Fix: never mutate; create a new copy and pass it to the setter (immutable update).
Mutation vs new copy
  1. 1.user.city = "Delhi": same object mutated

  2. 2.setUser(user): old === new, re-render skipped, screen same

  3. 3.setUser({ ...user, city: "Delhi" }): a new object

  4. 4.Reference changed: React re-renders, screen shows Asha: Delhi

27.3 Fix: a new object with spread

  • { ...user, city: "Delhi" } copies all old properties, then overwrites city.
  • setUser gets a brand-new object, so React knows state changed.
React (JSX)
function Profile() {  const [user, setUser] = useState(    { name: "Asha", city: "Pune" }  );  function moveToDelhi() {    setUser({ ...user, city: "Delhi" });  }   return (    <button onClick={moveToDelhi}>      {user.name}: {user.city}    </button>  );}
Output
-- before click --[button] Asha: Pune-- after click --[button] Asha: Delhi

27.4 Arrays: add, remove, update

  • push, splice and sort mutate the original array, so do not use them on state.
  • Add: [...items, item] copies and appends.
  • Remove: items.filter(i => i.id !== id) keeps everything except that id.
  • Update one item: items.map returns a new array; the matching item becomes { ...i, qty }, the rest are returned as they are.
React (JSX)
const [items, setItems] = useState([]); function addItem(item) {  setItems([...items, item]);} function removeItem(id) {  setItems(items.filter((i) => i.id !== id));} function changeQty(id, qty) {  setItems(items.map((i) =>    i.id === id ? { ...i, qty } : i  ));}
OperationAvoid (mutates)Use (new array)
Addpush, unshift[...items, item]
Removesplicefilter
Update one itemitems[i].qty = 2map + { ...i, qty }
SortsorttoSorted (or [...items].sort())
ReversereversetoReversed

Checkpoint: will the list sort? No. sort mutates and returns the same array (the log prints true), so React sees the same reference. Use toSorted, which returns a new sorted array.

React (JSX)
function sortByPrice() {  const sorted = items.sort(    (a, b) => a.price - b.price  );  console.log(sorted === items);  setItems(sorted);}
Output
trueScreen: list same order

27.5 Nested objects: copy every level

  • Spread is a shallow copy: only the top level is new.
  • { ...user } still shares the same address object, so editing next.address.city also changes the old state.
  • Spread every level down to the one that changes.
React (JSX)
// Wrong: shallow copy, old state also changedconst next = { ...user };next.address.city = "Delhi";setUser(next);
React (JSX)
// Right: new copy at every levelsetUser({  ...user,  address: { ...user.address, city: "Delhi" },});

27.6 Derived state: do not store total

  • Keeping total in its own state means syncing it on every add and remove.
  • Forget once and you get Items 0 but Total 999.
  • Rule: if a value can be calculated from existing state, calculate it during render instead of storing it.
React (JSX)
// Wrong: total kept in state; after remove: Items 0, Total 999const [items, setItems] = useState([]);const [total, setTotal] = useState(0); function addItem(item) {  setItems([...items, item]);  setTotal(total + item.price);}
React (JSX)
// Right: total derived from items, always in syncconst [items, setItems] = useState([]);const total = items.reduce(  (sum, i) => sum + i.price * i.qty, 0); function addItem(item) {  setItems([...items, item]);}

27.7 Lifting state up

  • Header shows the cart count, ProductList has the Add button; if items lived in ProductList, Header could not read it.
  • Move the state to the closest common parent, App.
  • Header gets count={items.length}; ProductList gets onAdd={addItem}.
  • Clicking Add Shoes updates App's state and Header shows Cart (1).
React (JSX)
function App() {  const [items, setItems] = useState([]);   function addItem(item) {    setItems([...items, item]);  }   return (    <>      <Header count={items.length} />      <ProductList onAdd={addItem} />    </>  );}
Output
-- start --# Cart (0)[button] Add Shoes-- after clicking Add Shoes --# Cart (1)[button] Add Shoes
Lifting state up
  1. 1.Shared state lives in the parent: App holds items

  2. 2.Props go down: count to Header, onAdd to ProductList

  3. 3.Child calls the callback: onAdd(shoes)

  4. 4.Parent updates state, both children re-render in sync

One source of truth for the cart

27.8 Common mistakes

  • Mutating then calling the setter with the same object or array.
  • Using sort/push/splice on state.
  • Shallow-copying a nested object and editing the inner object.
  • Storing derived values (total, count, filtered list) in their own state.
  • Myth: new copies are slow. Spread copies only the top level and reuses unchanged inner objects, and a new reference lets React detect changes with one cheap comparison.

27.9 Rules for object and array state

  1. Never mutate state: use spread, filter, map, toSorted.
  2. Copy every level of a nested object you change.
  3. Do not store values you can calculate.
  4. Shared data goes in the closest common parent.

27.10 Interview tips

  • State is treated as immutable: create a new copy with spread, map or filter and give it to the setter.
  • React compares references (Object.is) to decide whether to re-render; mutation keeps the same reference.
  • Spread is shallow; nested updates need a copy at every level.
  • Do not keep derived values in state; compute them during render.
  • Lift shared state to the closest common parent: single source of truth.