React · Junior · Question 15 of 75
What's the right way to add an item to an array in state?
- 1
items.push(item); setItems(items); - ✓Correct answer:
setItems([...items, item]); - 3
setItems(items.concat).push(item);
Explanation
State must be updated immutably - by creating a new array. push mutates the existing array, and the reference doesn't change. Non-mutating methods: spread, concat, filter, map, slice, toSorted(). Removal: items.filter(i => i.id !== id).