Repaso
Español
Frontend & WebIntermediateFE-11

Why doesn't this re-render?

const [items, setItems] = useState([]);
function add(x) {
  items.push(x);
  setItems(items);
}

Options

  1. useState cannot store arrays, only primitives
  2. The same array reference is set, so React skips it (Correct option)
  3. push is asynchronous in plain JavaScript code
  4. setItems needs to be awaited before the push

Answer

The same array reference is passed; React compares with Object.is and skips the update. Create a new array: setItems([...items, x])

Why

React decides whether to re-render by checking if the new state is a different object than the old one.

push changes the existing array, so setItems(items) passes the SAME array, React sees no change and does nothing.

Always create a new array or object: setItems(prev => [...prev, x]).

Remember

Never mutate React state; create a new copy.

Key terms

Practice this question in Repaso