How to Update Objects and Arrays in React State
Adding, changing and removing items in React state without mutating it.
When you keep an object or an array in React state, it's tempting to change it directly and then call the setter. React decides wether to re-render by checking if the new state is a different object from the old one. If you change the old one in place, it's still the same object, so React may skip the update and your screen won't change.
Never change state directly. Always pass a new object or array to the setter.
The Mistake
Here's what not to do:
const [user, setUser] = useState({ name: "Jim", email: "jim@example.com" })const updateName = () => {user.name = "Pam"setUser(user) // same object, React skips the re-render}
Updating an Object
Create a new object with the spread operator, copying the old values and overriding the one that changed:
setUser({ ...user, name: "Pam" })
For nested objects, spread each level you change:
setUser({...user,address: { ...user.address, city: "Chicago" },})
Updating an Array
Array methods like push, splice and sort change the original array, so
avoid them on state. (There's more on that in
When to Use slice and splice.)
Use methods that return a new array instead.
Adding an item:
setTodos([...todos, { id: 4, title: "Write a blog post", done: false }])
Removing an item with filter:
setTodos(todos.filter((todo) => todo.id !== id))
Updating an item with map:
setTodos(todos.map((todo) => (todo.id === id ? { ...todo, done: !todo.done } : todo)))
map returns a new array, and the spread creates a new object for the item that
changed. Every other item is left as it was.
Sorting a copy:
setTodos([...todos].sort((a, b) => a.title.localeCompare(b.title)))
Using the Previous State
When the new state depends on the old state, pass a function to the setter. React calls it with the latest value:
const addTodo = (title) => {setTodos((prevTodos) => [...prevTodos,{ id: Date.now(), title, done: false },])}
This avoids bugs when several updates happen close together, since each one builds on the result of the last.
Copy, change, then set. Treat state as read-only and React will always know when to update.
Have some feedback on this post? .