React decides whether state changed by comparing the new value with the old one using Object.is, which for objects and arrays is a reference check. So: treat state as read-only, and to change something, pass the setter a new object or array.
Mutation breaks this in several ways:
- No render.
todo.done = true; setTodos(todos)passes the same array. React sees no change and drops the update. - Updates appear later, at random. The mutation stays in the object, so the next unrelated render shows it.
- Memoization and effects miss it.
memo,useMemo,useCallbackand effect dependencies all compare by reference, so a mutated object looks unchanged. The React Compiler's automatic memoization relies on the same rule of React: props and state are immutable. - The past gets rewritten. Earlier renders' closures, logged objects and any undo history share the mutated object. Strict Mode's double calls also repeat mutations inside updaters and reducers.
To update, copy everything on the path from the state's root to the change and reuse the rest:
- Objects:
{ ...person, name }. Spread copies one level, so a nested change needs a copy at each level:{ ...person, address: { ...person.address, city } }. - Arrays: add with
[...items, item], remove withfilter, replace withmap, insert withtoSplicedor slices, sort withtoSortedor a copy. Avoidpush,splice,sort,reverseand index assignment on the state array. - An object in an array:
items.map(i => i.id === id ? { ...i, done: true } : i).
Mutating something you created in the same handler is fine: const next = [...items]; next.push(item); setItems(next) never touches the state.
When nesting gets deep, flatten the state, or use Immer, which lets you write mutating code against a draft and produces the copies for you.