
Why Mutating State Doesn't Update the Screen in React
- كاتب موثّق
- React 19
محتويات المقال
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
push, splice, task.done = true, then call the setter and React re-renders with the new data.
What actually happens
The setter compares references, not contents
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.
Mutation rewrites the past
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
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} />;}import { useState } from "react";type Task = { id: string; title: string; done: boolean };export function TaskList({ initial }: { initial: Task[] }) { // readonly: TypeScript now rejects push, splice and sort on tasks const [tasks, setTasks] = useState<readonly Task[]>(initial); function addTask(title: string) { setTasks([...tasks, { id: crypto.randomUUID(), title, done: false }]); } function toggle(task: Task) { // A new array, and a new object only for the task that changed setTasks(tasks.map((t) => (t.id === task.id ? { ...t, done: !t.done } : t))); } 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
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 } };}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:
tasks.push(task) | [...tasks, task] | |
tasks.splice(i, 1) | tasks.filter((t) => t.id !== id) | |
task.done = true | tasks.map(...) returning { ...t, done: true } for the match | |
tasks.sort(byDate) | tasks.toSorted(byDate) or copy first | |
profile.name = name | { ...profile, name } |
How to apply it in your project
Search for mutations on state Grep your components for .push(,.splice(,.sort(,.reverse(and assignments likeitem.done =on values that came fromuseStateor props. Each one is a candidate bug, even if the screen looks right today.Replace them with new values Use the table above: spread to add, filterto remove,mapwith a spread to edit one item,toSortedto sort. For nested data, copy every level on the path to the change.Let TypeScript guard the rule Type state as readonly Task[]orReadonly<Profile>so the compiler rejectspush,sortand field assignments before they reach a user.Keep state flat When 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,filterandtoSorted, 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.
التعليقات (0)