How to Update Lists in React
In React, updating lists in state requires a non-mutating approach to
ensure components re-render correctly. This article provides a
straightforward guide on how to safely add, remove, and modify items in
a React list using immutable state update patterns like
map(), filter(), and the spread operator.
The Rule of Immutability
In React, you should never mutate state directly. Instead of using
array methods that modify the original array (like push(),
pop(), or splice()), you must always create a
new array. This allows React to detect the state change and trigger a
re-render.
Adding Items to a List
To add an item to an array in React state, use the ES6 spread
operator (...). This creates a new array containing all
existing items plus the new one.
const [items, setItems] = useState(['Apple', 'Banana']);
const addItem = (newItem) => {
setItems([...items, newItem]);
};To add an item to the beginning of the list, place the new item
before the spread operator: [newItem, ...items].
Removing Items from a List
The cleanest way to remove an item from a list is using the
.filter() method. This method returns a new array
containing only the elements that meet a specified condition, leaving
the original array untouched.
const [items, setItems] = useState([
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' }
]);
const removeItem = (idToRemove) => {
setItems(items.filter(item => item.id !== idToRemove));
};Updating Items in a List
To modify specific items within a list, use the .map()
method. This allows you to loop through the array, find the target item,
update its values, and return a new array.
const [items, setItems] = useState([
{ id: 1, name: 'Apple', quantity: 1 },
{ id: 2, name: 'Banana', quantity: 1 }
]);
const updateQuantity = (id, newQuantity) => {
setItems(items.map(item => {
if (item.id === id) {
// Return a new object with the updated property
return { ...item, quantity: newQuantity };
}
// Return the unchanged item
return item;
}));
};By using these functional array methods, you ensure your React list updates are predictable, bug-free, and trigger UI updates reliably.