الانتقال إلى المحتوى
FrontendReact· 7 دقائق للقراءة

Why Mutating State Doesn't Update the Screen in React

React compares state by reference. Change what's inside, and the setter sees nothing new.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • React 19
محتويات المقال

A user writes in: "I add a task and nothing happens. Then I type in the search box and my task suddenly shows up." The code looks innocent: it pushes the new task into the tasks array, then calls setTasks(tasks). The setter is right there, so React should know. It doesn't, and the task appearing later, at a random moment, is the clue to why.

The common misconception

The belief: the setter is the signal. Change the data however you like, push, splice, task.done = true, then call the setter and React re-renders with the new data.

It's a natural belief if you've used other tools. Many reactive UI libraries track mutations by wrapping your objects in proxies, and plenty of backend code updates objects in place. In React it even half works: mutate, and the next render that happens for any other reason will show your change, which is exactly why the task above appears after typing. That accidental success is what makes the bug so confusing.

What actually happens

The setter compares references, not contents

When you call setTasks(next), React compares next with the current state using Object.is. If they're identical, React skips re-rendering the component and its children. For arrays and objects, identical means the same reference. tasks.push(task) changes what's inside the array, but it's still the same array, so setTasks(tasks) hands React the value it already has. No render. The new task sits in memory until something else, like typing in the search box, re-renders the list, and the render reads the mutated array.

Why doesn't React just look inside? A deep comparison on every update would cost time in proportion to the size of your data, and watching objects for edits would mean wrapping them in proxies. React does neither: it never touches your objects. That's why you can keep any object in state, however large, at no extra cost, as long as you replace it instead of editing it.

Mutation rewrites the past

The array you pushed into is also the one the previous render used. React's docs call each render's state a snapshot; mutating it changes that snapshot after the fact. Logs you printed earlier now show the new contents, and any code that compares old and new values sees "no change". That includes memo, which compares props with Object.is, and Effect and useMemo dependency checks. The docs spell out the bargain: if you never mutate, prevObj === obj is enough to know nothing inside changed. That one fast check powers React's optimizations, and features like undo, a change history or resetting a form get much easier when old values are never overwritten.

Make a new value instead

The fix is to treat state as : never change it, replace it. Build a new array or object that differs where you need it, and pass that to the setter:

TSX TaskList.tsx
import { useState } from "react";type Task = { id: string; title: string; done: boolean };export function TaskList({ initial }: { initial: Task[] }) {  const [tasks, setTasks] = useState(initial);  function addTask(title: string) {    tasks.push({ id: crypto.randomUUID(), title, done: false });    setTasks(tasks); // same array: Object.is sees no change  }  function toggle(task: Task) {    task.done = !task.done; // edits an object the last render showed    setTasks([...tasks]); // new array, same old task objects  }  return <TaskView tasks={tasks} onAdd={addTask} onToggle={toggle} />;}

TaskView just draws the list. In the wrong version, addTask never renders, as described above. toggle is the sneakier bug: the spread creates a new array, so TaskList does re-render and the fix looks done. But the task object inside is the same one, now edited in place. If a row component is wrapped in memo, it gets the same task reference as last time, skips its render, and the checkbox stays stale. The right version replaces only the task that changed and keeps the rest, so a memoized row re-renders exactly when its own task changes.

Copy all the way up for nested data

Spread syntax copies one level deep. To change a field two levels down, copy each level on the way to it:

TypeScript profile.ts
type Profile = { name: string; address: { city: string; street: string } };// Copy every level on the path to the changed fieldexport function withCity(profile: Profile, city: string): Profile {  return { ...profile, address: { ...profile.address, city } };}

The objects you don't touch, like everything else in profile, are shared between the old and new state, which is safe precisely because nobody mutates them. Here's the cheat sheet for everyday changes:

ChangeAvoid (mutates)Prefer (new value)
Add an itemtasks.push(task)[...tasks, task]
Remove an itemtasks.splice(i, 1)tasks.filter((t) => t.id !== id)
Change one itemtask.done = truetasks.map(...) returning { ...t, done: true } for the match
Sort or reversetasks.sort(byDate)tasks.toSorted(byDate) or copy first
Change a fieldprofile.name = name{ ...profile, name }

How to apply it in your project

  1. Search for mutations on stateGrep your components for .push(, .splice(, .sort(, .reverse( and assignments like item.done = on values that came from useState or props. Each one is a candidate bug, even if the screen looks right today.
  2. Replace them with new valuesUse the table above: spread to add, filter to remove, map with a spread to edit one item, toSorted to sort. For nested data, copy every level on the path to the change.
  3. Let TypeScript guard the ruleType state as readonly Task[] or Readonly<Profile> so the compiler rejects push, sort and field assignments before they reach a user.
  4. Keep state flatWhen updates need three levels of spread, store related data side by side, for example tasks in one list and the selected task as an id, so each update replaces one small value.

Key takeaways

  • React compares state with Object.is: the same array or object reference means no re-render, whatever changed inside.
  • Mutation also edits the previous render's snapshot, which breaks memo, dependency checks and debugging.
  • Replace instead of mutate: spread, map, filter and toSorted, copying every level on the path to a nested change.
  • A new outer array with old, edited objects inside is still a mutation; mutating an object you just created is fine.

📚 المصادر

  1. Updating Objects in State — React
  2. Updating Arrays in State — React
  3. useState — React API Reference
  4. Array.prototype.toSorted() — MDN

التعليقات (0)