Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 132 ยท State and Events

Objects and Arrays in State

Learn why React state must be treated as immutable, how to update objects, nested objects and arrays with spread, map and filter, why mutation fails, and how Immer-style produce works.

Numbers, strings and booleans are easy to keep in state: you pass a new one to the setter. Real UIs hold richer data, such as a user profile (an object), a to-do list (an array of objects) or a shopping cart. Here beginners hit the most common React bug of all: they change the object or array that is already in state, call the setter, and nothing happens on screen.

The rule that prevents this is simple to say and takes practice to follow: treat state as read-only. To change it, replace it with a new copy. This lesson shows why the rule exists, then gives you a toolkit of patterns for updating objects, nested objects and arrays, and finally shows how libraries such as Immer let you write mutating-looking code safely.

Why mutation breaks rendering

State can hold any JavaScript value, including objects. But you must never change that object in place. React decides whether to re-render by comparing the old and new state with Object.is. For objects and arrays that means same reference (the same box in memory), not "same contents". If you mutate the object and hand the same reference back to the setter, React concludes nothing changed.

Mutating state does not update the screen (fails on purpose)

Click "Mutate" three times: the console logs mutated: score is now 1, 2, 3, yet the screen keeps showing 0 and no render line appears. The object in memory did change, but React was told "the new state is the same object as before" and skipped the render. Now click "Replace": the new object differs from the old one, React renders, and the screen jumps to 4, because it picks up the earlier hidden mutations as well. That inconsistency is the real danger: mutated state shows up randomly, later, whenever some other update happens to cause a render.

Mutation causes more trouble than missed renders: it breaks features that compare old and new values (memo, effect dependencies, undo history), it corrupts earlier "snapshots", and it makes bugs hard to reproduce. Immutability gives you predictable updates and cheap change detection, because "did it change?" becomes a single reference comparison.

"Immutable" does not mean the data never changes. It means you never modify an object in place. You make a new object with the changes and give React that.

Updating objects with spread

To change an object, create a copy that has the new values. The spread syntax { ...old, key: newValue } copies every property of old and then overrides key.

Updating an object with spread

Two techniques are worth noticing. First, ...profile copies the fields you are not changing, so you do not need to list them. Second, [e.target.name]: e.target.value uses a computed property name, which lets one handler serve many inputs (more in Controlled Inputs and Forms). If the new value depends on the old state in a way that matters across several updates, use the updater form: setProfile((prev) => ({ ...prev, [name]: value })), as explained in How State Updates Work.

Spread makes a shallow copy: it copies the top-level properties, but any nested object is still shared between the old and the new object. That matters as soon as your state has depth.

Nested objects

Suppose state looks like { name: 'Ada', address: { city: 'London', zip: 'N1' } }. To change the city you must copy every level on the path to the changed value.

Updating a nested object

After clicking, the original snapshot is untouched (it still says London) and person.address is a different object, so the answer to "Same address object as before?" becomes false. Had we written person.address.city = 'Paris', both snapshots would have changed together.

Deeply nested updates get verbose, and that is a design signal: prefer flatter state when you can. Choosing a State Structure shows how to flatten and normalize. When you cannot, use the Immer approach at the end of this lesson.

Updating arrays

JavaScript arrays have two groups of methods. The mutating ones (push, pop, shift, unshift, splice, sort, reverse, and assigning arr[i] = x) change the array in place, so avoid them on state. The non-mutating ones (concat, slice, filter, map, toSorted, toReversed, toSpliced, with, and spread [...arr]) return a new array and are what you use.

You want to Avoid (mutates) Prefer (returns new array)
Add push, unshift [...arr, item], [item, ...arr]
Remove pop, shift, splice filter(x => x.id !== id)
Replace or edit arr[i] = x map(x => x.id === id ? changed : x)
Insert at position splice(i, 0, x) [...arr.slice(0, i), x, ...arr.slice(i)]
Sort or reverse sort(), reverse() toSorted(), toReversed() or copy first: [...arr].sort()

Here they are in one to-do list.

Add, toggle, remove, insert and sort

Study how each handler builds a brand-new array:

  • [...todos, newItem] copies the old items and adds one at the end.
  • todos.map(...) returns a new array in which exactly one element is replaced by a new object; the others are the same objects as before, so unchanged rows are cheap to compare. Note { ...t, done: !t.done } copies the to-do instead of editing it.
  • todos.filter(...) returns a new array without the removed element.
  • toSorted is the non-mutating version of sort. It is available in all current browsers and Node 20+. If you must support older environments, copy first: [...todos].sort(...).

Notice also the stable id used as the key (see Rendering Lists and Keys); array positions change when items move, ids do not.

A shallow copy of an array still contains the same item objects. After const copy = [...todos], copy[0].done = true changes the object shared by both arrays, which means it mutates state. Copy the array and any object you intend to change.

Updating an item inside a nested array

Combine the patterns. Suppose each list has its own items: lists: [{ id, title, items: [...] }]. To toggle one item, rebuild every level on the path: the outer array (map), the list object (spread) and the inner array (map).

JSX
setLists(
  lists.map((list) =>
    list.id !== listId
      ? list
      : {
          ...list,
          items: list.items.map((item) =>
            item.id === itemId ? { ...item, done: !item.done } : item
          ),
        }
  )
);

Notice the unchanged lists are returned as they are (: list), which keeps their references and avoids needless work further down the tree. It works, but you can already see why deep structures are painful.

Immer: write mutations, get immutable updates

Immer is a small library that lets you write update code that looks like mutation. You call produce(state, draft => { ... }); inside the callback draft is a special proxy that records your changes, and produce returns a new immutable object built from them, reusing everything you did not touch. Immer is not available in our editor, so this is read-only code that needs npm install immer:

JSX
import { produce } from 'immer';

function toggleItem(lists, listId, itemId) {
  return produce(lists, (draft) => {
    const list = draft.find((l) => l.id === listId);
    const item = list.items.find((i) => i.id === itemId);
    item.done = !item.done; // looks like mutation, but only changes the draft
  });
}

// Inside a component you can pass the same recipe to useState's setter:
setLists((current) => toggleItem(current, listId, itemId));

To see that there is no magic, here is a deliberately simplified produce built by hand. It deep-copies the state, lets you mutate the copy, and returns it. Real Immer is smarter (it copies lazily and shares unchanged parts, so it is faster and keeps references stable), but the contract is the same.

A hand-written produce

structuredClone copies plain data deeply (objects, arrays, dates, maps), though not functions. Our stand-in copies everything on every update, so every list gets a new identity and anything wrapped in memo would re-render; real Immer only creates new objects along the changed path. Use Immer (or useImmer / useImmerReducer from the use-immer package) when your state is deeply nested and the spread chains obscure the intent; do not reach for it for flat state, where map and spread are clearer and dependency-free.

Practical tips

  • Keep state flat and store ids rather than duplicating objects; it makes updates one-liners.
  • Don't copy more than you need. { ...obj, x: 1 } is shallow and cheap. Deep-copying everything with structuredClone or JSON on each keystroke is wasteful on big data.
  • Use map for "update one", filter for "remove one" and always return the other items unchanged.
  • Freeze while learning. Calling Object.freeze(obj) (shallow) on initial state makes accidental mutation in strict-mode modules throw a TypeError, which reveals mistakes quickly.
  • Remember non-plain values. Dates, Maps and Sets are also compared by reference. Create a new Map/Set (new Set(old).add(x)) instead of mutating the one in state.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A handler runs player.score++; setPlayer(player);. Why might the screen not update?

    React uses Object.is to compare old and new state. The mutated object is the same reference, so React sees no difference. Create a new object instead, such as setPlayer({ ...player, score: player.score + 1 }).
  2. 2. What does the spread syntax in { ...user, age: 31 } produce?

    Spread creates a new object (a shallow copy) and then the later key overrides age. Nested objects are still shared with the original.
  3. 3. Which line removes the todo with a given id without mutating the array?

    filter returns a new array that excludes the item. splice, pop and delete modify the existing array in place.
  4. 4. After const copy = [...todos] what does copy[0].done = true do?

    The array is new, but its elements are the same objects. Editing an element mutates the shared object. Replace the element with { ...copy[0], done: true } instead.
  5. 5. What does Immer's produce let you do?

    produce hands your recipe a draft that records changes and returns a new immutable result, sharing untouched parts of the old state.

Summary

  • Never mutate state objects or arrays; always give the setter a new object or array.
  • React detects change by reference, so a mutated-but-same object does not re-render (and causes confusing delayed updates).
  • Update objects with spread ({ ...old, key: value }); copy every level on the path to a nested value.
  • Use [...arr, x], filter, map, toSorted and slice for arrays; avoid push, splice, sort and index assignment.
  • Spread and [...arr] are shallow copies; edit items by replacing them with new objects.
  • Prefer flat state; use Immer (shown with a hand-written produce) when deep nesting makes spread code unreadable.

Next: Controlled Inputs and Forms