Updating objects and arrays

Topic 4 of 4 in Interactivity & state6 min readIntermediateFree course

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

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

Mutating: user.name = “Asha” then setUser(user) gives the same object, so old and next state are equal and React skips the render. Copying: setUser({ …user, name: “Asha” }) creates a new object, so old and next state differ and React re-renders with the new value.

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:

JSX
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

JSX
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:

JSX
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

JSX
setCart([...cart, { id: course.id, title: course.title, qty: 1 }]);

Removing

JSX
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:

JSX
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:

JSX
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

JSX
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:

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

Exercise

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.

JavaScript
import { useState } from 'react';

export function TodoList() {
  const [todos, setTodos] = useState([]);
  const [text, setText] = useState('');

  // your code here
}

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, filter to remove, map to replace, and toSorted/toReversed to reorder.
  • Avoid push, splice, sort, reverse and direct assignment on state.