Topic 19 of 54
Updating Arrays in State
Overview
Just like objects, Arrays in React state must be treated as Immutable. You cannot use methods that mutate the original array, such as `.push()`, `.pop()`, `.splice()`, or `.sort()`. Instead, you must use methods that return a brand new array, such as `.map()`, `.filter()`, or spreading `[...oldArray, newItem]`.
Syntax
Spreading `...prev` takes all the elements out of the old array and puts them into a brand new array bracket `[]`.
Adding to an Array
jsx
const [items, setItems] = useState(['Apple', 'Banana']);
const addItem = (newItem) => {
// ❌ BAD: items.push(newItem)
// ✅ GOOD: Spread the old array, add the new item at the end
setItems(prev => [...prev, newItem]);
// Or add to the beginning
// setItems(prev => [newItem, ...prev]);
};`.filter()` is perfect for deletions. `.map()` is perfect for modifying a specific item based on its ID.
Removing and Updating Items
jsx
// Removing an item (Use .filter)
const removeItem = (idToRemove) => {
// Returns a new array containing everything EXCEPT the item to remove
setItems(prev => prev.filter(item => item.id !== idToRemove));
};
// Updating a specific item (Use .map)
const markAsDone = (idToUpdate) => {
setItems(prev => prev.map(item =>
item.id === idToUpdate
? { ...item, isDone: true } // Return modified copy
: item // Return as-is
));
};Common Pitfalls
- Using `.splice()` to remove an item. `.splice()` mutates the original array and returns the removed items, causing bugs.
- Using `.sort()` directly. `.sort()` mutates the array. You must copy it first: `[...arr].sort()`.
Interview Tips
- Memorize this mapping for React state: Replace `.push()` with `[...arr, item]`. Replace `.splice()` with `.filter()`. Replace direct mutation `arr[i] = x` with `.map()`.
Real-World Example
A Shopping Cart where you can add items, remove items, or update quantities.
example
jsx
function ShoppingCart() {
const [cart, setCart] = useState([]);
const increaseQuantity = (productId) => {
setCart(prev => prev.map(item =>
item.id === productId
? { ...item, qty: item.qty + 1 }
: item
));
};
const removeFromCart = (productId) => {
setCart(prev => prev.filter(item => item.id !== productId));
};
}