Updating objects and arrays
Overview
So far, state has held simple values like numbers and booleans. Real apps store objects and arrays: a user profile, a form, a list of cart items. These are mutable in JavaScript — but in React state you must treat them as if they were immutable, and replace them with new copies when they change.
Why mutation doesn’t work
function Profile() {
const [user, setUser] = useState({ name: 'Ana', city: 'Pune' });
function handleRename() {
user.name = 'Asha'; // ✗ mutating state
setUser(user); // same object
}
// The screen doesn't update.
}When you call a setter, React compares the new value with the old one using Object.is. You passed the same object, so React concludes nothing changed and skips the render.
Even when mutation seems to work (because something else triggered a render), it causes subtle bugs: previous renders’ snapshots change under you, memoised components show stale data, and debugging tools can’t show you history.
Updating objects
Create a new object with the spread syntax, then override what changed:
function handleRename() {
setUser({ ...user, name: 'Asha' });
}{ ...user } copies all of user’s properties into a new object; properties after it overwrite the copies.
One handler for many fields
function ProfileForm() {
const [form, setForm] = useState({ name: '', email: '', city: '' });
function handleChange(e) {
setForm({ ...form, [e.target.name]: e.target.value });
}
return (
<form>
<input name="name" value={form.name} onChange={handleChange} />
<input name="email" value={form.email} onChange={handleChange} />
<input name="city" value={form.city} onChange={handleChange} />
</form>
);
}[e.target.name] is a computed property name — it uses the input’s name attribute as the key.
Nested objects
Spread is shallow: it copies one level. To change something nested, copy each level on the way down:
const [course, setCourse] = useState({
title: 'React',
author: { name: 'Priya', social: { github: 'priya' } },
});
function updateGithub(handle) {
setCourse({
...course,
author: {
...course.author,
social: { ...course.author.social, github: handle },
},
});
}If this gets painful, it’s a sign the state is too deeply nested — flatten it (see Structuring state), or use useReducer or the Immer library, which lets you write mutating-style code that produces immutable updates.
Updating arrays
Arrays work the same way: produce a new array instead of changing the existing one.
| Goal | ✗ Mutates | ✓ Returns a new array |
|---|---|---|
| add | push, unshift |
[...arr, item], [item, ...arr] |
| remove | splice, pop, shift |
filter |
| replace / update | arr[i] = x |
map, with(i, x) |
| reorder | sort, reverse |
toSorted, toReversed, or copy first |
| insert in the middle | splice |
[...arr.slice(0, i), item, ...arr.slice(i)], toSpliced |
Adding
setCart([...cart, { id: course.id, title: course.title, qty: 1 }]);Removing
setCart(cart.filter((item) => item.id !== idToRemove));Updating one item
Use map, returning a new object for the item that changes and the same object for the rest:
function increaseQty(id) {
setCart(
cart.map((item) =>
item.id === id ? { ...item, qty: item.qty + 1 } : item
)
);
}A subtle mistake is to copy the array but mutate the item inside it:
const next = [...cart];
next[0].qty += 1; // ✗ the item object is shared with the old state
setCart(next);The array is new, but the object inside it is the same one the previous state holds. Always replace the objects you change.
Sorting
const sorted = courses.toSorted((a, b) => a.title.localeCompare(b.title));toSorted, toReversed, toSpliced and with are the non-mutating versions of the classic array methods, supported in all modern browsers.
With updater functions
When several updates might happen in a row, combine these patterns with updater functions:
setCart((prev) => [...prev, newItem]);
setCart((prev) => prev.filter((i) => i.id !== id));Why immutability is worth it
- Change detection is cheap. React (and memoisation) only needs
old !== new, not a deep comparison. - Snapshots stay correct. Each render’s state is a fixed record — perfect for undo/redo and time-travel debugging.
- Bugs are easier to trace. State only changes through setters, so you know where every change came from.
Quick check: before calling a setter with an object or array, ask “is this a new object?” If you got it by mutating the old one, it isn’t.
A to-do list
Build TodoList with an input and an “Add” button, and a list of todos ({ id, text, done }). Implement: add (generate the id with crypto.randomUUID()), toggle done with a checkbox, delete with a button, and “Clear completed”. Never mutate the array or the todo objects.
import { useState } from 'react';
export function TodoList() {
const [todos, setTodos] = useState([]);
const [text, setText] = useState('');
// your code here
}import { useState } from 'react';
export function TodoList() {
const [todos, setTodos] = useState([]);
const [text, setText] = useState('');
function handleAdd() {
if (!text.trim()) return;
setTodos([...todos, { id: crypto.randomUUID(), text: text.trim(), done: false }]);
setText('');
}
function handleToggle(id) {
setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
}
function handleDelete(id) {
setTodos(todos.filter((t) => t.id !== id));
}
function handleClearCompleted() {
setTodos(todos.filter((t) => !t.done));
}
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} aria-label="New todo" />
<button onClick={handleAdd}>Add</button>
<ul>
{todos.map((t) => (
<li key={t.id}>
<label>
<input type="checkbox" checked={t.done} onChange={() => handleToggle(t.id)} />
{t.text}
</label>
<button onClick={() => handleDelete(t.id)}>Delete</button>
</li>
))}
</ul>
<button onClick={handleClearCompleted}>Clear completed</button>
</div>
);
}Summary
- Treat objects and arrays in state as read-only: replace them, don’t mutate them.
- React compares old and new state with
Object.is; a mutated object is the same object, so nothing re-renders. - Copy objects with spread:
{ ...user, name: 'Asha' }, and copy every level you change in nested objects. - For arrays use
[...arr, x]to add,filterto remove,mapto replace, andtoSorted/toReversedto reorder. - Avoid
push,splice,sort,reverseand direct assignment on state.