All posts
ReactOctober 29, 20268 min read

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.

F
Fepiq Team
Fepiq

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.

Why you must not change state directly

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 tool you need: the spread operator

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.

js
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.

Quick reference: wrong way vs right way

GoalWrong (changes the original)Right (makes a new copy)
Add an itemitems.push(x)[...items, x]
Remove an itemitems.splice(i, 1)items.filter(item => item.id !== id)
Change an itemitems[i].done = trueitems.map(item => item.id === id ? { ...item, done: true } : item)
Change an object fielduser.name = 'Sam'{ ...user, name: 'Sam' }

Step 1: Add an item to an array in state

Let us build a small list of names. The user types a name, clicks a button, and the name is added.

jsx
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 React

Step 2: Remove an item from an array in state

To 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.

jsx
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.

Step 3: Change one item inside an array

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.

jsx
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.

Step 4: Update an object in state

Objects work the same way. Copy with spread, then write the field you want to change after it.

jsx
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.

Updating a form with many fields

One handler can update many fields if each input has a name attribute.

jsx
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.

Step 5: Update a nested object

If an object contains another object, you must copy each level that you change.

jsx
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.

A tip: use the updater function when the new value depends on the old one

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.

jsx
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.

Common mistakes to avoid

  • Using push(), pop(), splice() or sort() directly on state. These change the original array.
  • Writing state.name = 'x' and expecting the screen to update. React will not notice.
  • Forgetting ...old when updating an object, which erases the other fields.
  • Putting the same key on many list items. Give each item a unique id and use it as the key.

Frequently asked questions

How do I add an item to an array in React state?+

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.

Why does React not update when I use push() on state?+

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.

How do I remove an item from an array in React state?+

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.

How do I update one property of an object in React 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.

What is the spread operator in React?+

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.

Summary

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 Beginners

Need help turning your idea into a real web app? Talk to the Fepiq team.

Contact Fepiq

Get new posts in your inbox

Occasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.

Keep reading

Related posts

All posts

Let's build something

Ready to ship your next product with Fepiq?

Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.