How do you update an array element in state?
Main idea
In React, state must be immutable -
you cannot change an array directly (push, splice, index assignment).
Instead you need to create a new array with the needed changes
and pass it to setState.
Example 1. Updating an element by index
javascript
function App() {
const [numbers, setNumbers] = useState([10, 20, 30]);
const updateSecond = () => {
setNumbers(prev =>
prev.map((num, i) => (i === 1 ? num + 5 : num))
);
};
return (
<div>
<p>{numbers.join(", ")}</p>
<button onClick={updateSecond}>Change second element</button>
</div>
);
}map() creates a new array
We change only the element where i === 1
The rest stay unchanged
Result:
javascript
[10, 20, 30] → [10, 25, 30]Example 2. Updating by condition (for example, by id)
State very often holds objects:
javascript
const [users, setUsers] = useState([
{ id: 1, name: "Alex", active: false },
{ id: 2, name: "Tim", active: true },
]);You want to update a specific user:
javascript
const toggleActive = (id) => {
setUsers(prev =>
prev.map(user =>
user.id === id ? { ...user, active: !user.active } : user
)
);
};What happens:
map()creates a new array- if the id matches -> we create a new object (immutably)
- otherwise we return the old object
Example 3. Updating by index (array copy variant)
You can do it manually:
javascript
const [items, setItems] = useState(["apple", "banana", "cherry"]);
const changeBanana = () => {
const copy = [...items]; // create a copy
copy[1] = "mango"; // change the element in the copy
setItems(copy); // update state
};Never do this:
javascript
items[1] = "mango"; // mutates the array
setItems(items); // React will not notice the changeExample 4. Updating a nested array in an object
javascript
const [cart, setCart] = useState({
items: [
{ id: 1, name: "Shirt", qty: 1 },
{ id: 2, name: "Pants", qty: 2 },
],
});
const incrementQty = (id) => {
setCart(prev => ({
...prev,
items: prev.items.map(item =>
item.id === id ? { ...item, qty: item.qty + 1 } : item
),
}));
};Here:
- we copy the
cartobject (...prev) - inside it we update the
itemsarray immutably throughmap()
5. When to use which approach
| Task | Approach |
|---|---|
| Change by index | map() or a copy with [...arr] |
Change by id | map() with a condition |
| Update a nested object | Copy both the outer and inner levels |
| Add an element | [...arr, newItem] |
| Remove an element | arr.filter(...) |
Summary
| What not to do | What to do instead |
|---|---|
array[index] = value | setArray(prev => prev.map(...)) |
array.push(value) | setArray(prev => [...prev, value]) |
array.splice(i,1) | setArray(prev => prev.filter(...)) |
array.sort() | setArray(prev => [...prev].sort(...)) |
Remember
Never mutate the state array directly. Always create a new array or object. React compares references, not content. Use
map(),filter(),slice(), spread (...).
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.