How to Update an Array or Object in React State
Learn how to update an array or object in React state the right way. Add, remove and change items with simple, copy-pasteable examples for beginners.
Learn how to update an array or object in React state the right way. Add, remove and change items with simple, copy-pasteable examples for beginners.
How do you update an array or an object in React state? You never change the old value directly. Instead, you make a fresh copy with your change inside it, and you give that copy to the state setter function. That one rule is the answer, and the rest of this guide shows you how to follow it with simple examples.
This guide is for absolute beginners. If you are not sure what state is, read our guide on the useState hook first. Every new word is explained the first time it appears.
State is a value that React remembers between renders. A render is when React draws your component on the screen. React only draws again when you call the setter function, for example setItems. React also checks whether the new value is a different value from the old one.
Arrays and objects are stored by reference. That means a variable holds a link to the array, not the array itself. If you push a new item into the same array, the link stays the same. React sees the same link, thinks nothing changed, and may not update the screen.
The safe habit is simple: treat state as read-only. Make a copy, change the copy, and pass the copy to the setter.
The spread operator is three dots (...). It copies everything from an array or an object into a new one. You will use it all the time in React.
const fruits = ['apple', 'banana'];
const moreFruits = [...fruits, 'cherry'];
console.log(fruits); // ['apple', 'banana']
console.log(moreFruits); // ['apple', 'banana', 'cherry']Line 1 creates an array with two items. Line 2 builds a brand new array: ...fruits copies the old items, then 'cherry' is added at the end. The original array is untouched, which is exactly what React wants.
| Goal | Wrong (changes the original) | Right (makes a new copy) |
|---|---|---|
| Add an item | items.push(x) | [...items, x] |
| Remove an item | items.splice(i, 1) | items.filter(item => item.id !== id) |
| Change an item | items[i].done = true | items.map(item => item.id === id ? { ...item, done: true } : item) |
| Change an object field | user.name = 'Sam' | { ...user, name: 'Sam' } |
Let us build a small list of names. The user types a name, clicks a button, and the name is added.
import { useState } from 'react';
function NameList() {
const [names, setNames] = useState(['Ada', 'Linus']);
const [text, setText] = useState('');
function addName() {
setNames([...names, text]);
setText('');
}
return (
<div>
<input value={text} onChange={e => setText(e.target.value)} />
<button onClick={addName}>Add</button>
<ul>
{names.map(name => <li key={name}>{name}</li>)}
</ul>
</div>
);
}
export default NameList;Line 4 creates the names array in state with two starting names. Line 5 stores what the user is typing. Inside addName, setNames([...names, text]) builds a new array with all old names plus the new one, then gives it to React. The next line clears the input box. The list at the bottom is drawn with map(). We explain that in our guide to rendering lists in React.
New to lists in React? Learn how map() and the key prop work before you continue.
Read: How to Render a List in ReactTo remove an item, use the filter() method. It builds a new array that keeps only the items that pass a test. It never changes the old array, so it is safe to use with state.
function removeName(nameToRemove) {
setNames(names.filter(name => name !== nameToRemove));
}
// In the list:
<li key={name}>
{name}
<button onClick={() => removeName(name)}>Remove</button>
</li>The filter() test says: keep every name that is not equal to the one we want to remove. The result is a new array without that name. The button uses an arrow function, () => removeName(name), so the removal runs only when the button is clicked and not while the page is drawing.
Now imagine a to-do list where each task is an object with an id, a title and a done flag. To mark one task as done, use map(). It goes through every item and returns a new array. For the item you want to change, you return an updated copy. For all others, you return them as they are.
const [tasks, setTasks] = useState([
{ id: 1, title: 'Learn React', done: false },
{ id: 2, title: 'Build a project', done: false }
]);
function toggleTask(id) {
setTasks(
tasks.map(task =>
task.id === id ? { ...task, done: !task.done } : task
)
);
}Lines 1 to 4 create the tasks. In toggleTask, map() checks each task. If the id matches, it returns a new object: ...task copies all fields, then done: !task.done flips true to false or false to true. The later field wins, so the copy has the new done value. If the id does not match, the task is returned unchanged.
Objects work the same way. Copy with spread, then write the field you want to change after it.
const [user, setUser] = useState({ name: 'Sam', city: 'Paris' });
function changeCity() {
setUser({ ...user, city: 'Tokyo' });
}The new object gets name: 'Sam' from the copy, and then city is replaced with 'Tokyo'. If you forget ...user, the new object would contain only city and the name would be lost. That is a very common beginner mistake.
One handler can update many fields if each input has a name attribute.
const [form, setForm] = useState({ name: '', email: '' });
function handleChange(e) {
setForm({ ...form, [e.target.name]: e.target.value });
}
<input name="name" value={form.name} onChange={handleChange} />
<input name="email" value={form.email} onChange={handleChange} />The square brackets around e.target.name are called a computed key. They tell JavaScript to use the value of the input's name, such as "email", as the field to change. So one function works for every input.
If an object contains another object, you must copy each level that you change.
const [profile, setProfile] = useState({
name: 'Sam',
address: { city: 'Paris', country: 'France' }
});
function moveToTokyo() {
setProfile({
...profile,
address: { ...profile.address, city: 'Tokyo' }
});
}The outer ...profile copies name and address. Then address is replaced by a new object, built by copying the old address and changing only city. Keep your state flat when you can. Fewer levels means less copying.
If you add several items quickly, the names variable may be out of date. React gives you a safer form: pass a function to the setter. React calls it with the latest state.
setNames(prev => [...prev, 'Grace']);Here prev is the latest array. You return the new array built from it. You do not need this for every update, but it is a good habit for counters and lists.
Create a new array with the spread operator and pass it to the setter, for example setItems([...items, newItem]). Do not use push(), because it changes the original array and React may not re-render.
push() changes the array in place, so the variable still points to the same array. React compares the old and new value, sees no difference, and skips the update. Always give the setter a new array.
Use filter() to build a new array without that item, for example setItems(items.filter(item => item.id !== id)). filter() does not change the original array, so it is safe for state.
Copy the object with the spread operator and then write the property you want to change, like setUser({ ...user, city: 'Tokyo' }). The copy keeps the other properties and replaces only the one you set.
The spread operator (...) copies the items of an array or the fields of an object into a new one. React developers use it to create updated copies of state without changing the original.
Never edit state directly. To add, use [...items, x]. To remove, use filter(). To change one item, use map() with a spread copy. To update an object, use { ...obj, field: value }. Practice these four patterns on a small to-do list and they will soon feel natural.
Want to review the basics? Read our simple guide to the useState hook, then come back and practice these patterns.
Read: React useState for BeginnersNeed help turning your idea into a real web app? Talk to the Fepiq team.
Contact FepiqOccasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.
Keep reading
Learn SQL AND, OR and NOT operators with simple examples. See how to combine conditions in WHERE and avoid the common mistakes beginners make.
Learn JavaScript template literals with simple examples: backticks, ${} variables, and multi-line strings. A beginner-friendly guide you can copy and run.
Let's build something
Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.