Repaso
Español

In React, how should you update an array stored in state?

const [items, setItems] = useState(["a", "b"]);

function add() {
  // option A
  items.push("c");
  setItems(items);

  // option B
  setItems([...items, "c"]);
}

Options

  1. Option B: make a new array, so React sees a change (Correct option)
  2. Option A: mutate the array and set the same one
  3. Both options work in exactly the same way in React
  4. Neither option works in React for arrays in state

Answer

Option B: create a new array; React detects a new reference and re-renders

Why

React decides to re-render by comparing the old and new state with ===. If you mutate the same array (push) and pass it back, the reference is identical, so React may skip the update.

Always create a new value: [...items, x], items.filter(...), items.map(...); for objects { ...user, name: "Ana" }.

Treat state as immutable.

Remember

State is immutable: copy, don't mutate.

Key terms

Practice this question in Repaso