Array State
Overview
Just like Objects, Arrays stored in React State MUST be treated as Immutable.
You are strictly prohibited from using mutating array methods like .push(), .pop(), .splice(), or .sort(). These methods modify the existing array in memory. Because the memory address remains the same, React's diffing engine fails to detect the change, and your UI will not update.
To update an array in React, you must generate a brand new array using non-mutating methods.
- To add an item, use the Spread Operator [...].
- To remove an item, use .filter().
- To transform items, use .map().
This guarantees a new memory reference is created, triggering a flawless React re-render.
Syntax
function TaskManager() {
const [tasks, setTasks] = useState(['Code', 'Sleep']);
// ADD: Spread the old array, append the new item
const addTask = (newTask) => {
setTasks([...tasks, newTask]);
};
// REMOVE: Filter out the item that shouldn't be there anymore
const removeTask = (taskToRemove) => {
setTasks(tasks.filter(t => t !== taskToRemove));
};
// UPDATE/EDIT: Map over the array, change the one target, leave the rest alone
const updateTask = (oldTask, updatedTask) => {
setTasks(tasks.map(t => t === oldTask ? updatedTask : t));
};
}Common Pitfalls
- Using Array.push(): Writing
tasks.push('Eat'); setTasks(tasks);is the most common beginner mistake..push()modifies the existing array. React ignores the update. You must writesetTasks([...tasks, 'Eat']). - Using Array.sort() or Array.reverse(): These methods mutate the original array in place. If you need to sort an array in state, you must copy it first:
setTasks([...tasks].sort()).
Interview Questions
.splice() mutates the original array in place, violating React's immutability rule. .filter() returns a completely new array containing only the elements that passed the condition, making it perfectly safe for updating React state.
You simply place the new item before the spread operator: setArray([newItem, ...array]);
Real-World Example
Building a Shopping Cart: This encapsulates all three primary immutable array operations (Add, Remove, Update) required to build a fully functional enterprise shopping cart.
function ShoppingCart() {
const [cart, setCart] = useState([
{ id: 1, name: 'Apple', qty: 1 }
]);
const addToCart = (product) => {
// Check if the item already exists in the cart
const exists = cart.find(item => item.id === product.id);
if (exists) {
// UPDATE: Map the array, increase the qty of the specific item
setCart(cart.map(item =>
item.id === product.id ? { ...item, qty: item.qty + 1 } : item
));
} else {
// ADD: Spread old cart, add new item object
setCart([...cart, { ...product, qty: 1 }]);
}
};
const removeFromCart = (id) => {
// REMOVE: Filter out the item matching the ID
setCart(cart.filter(item => item.id !== id));
};
}Check Your Knowledge
Test your understanding of Array State with these quick questions.