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
- Option B: make a new array, so React sees a change (Correct option)
- Option A: mutate the array and set the same one
- Both options work in exactly the same way in React
- 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.