Sub topic 3
Treat state as read-only: replace, don't change
This chapter covers the rule that governs every pattern later in this tutorial: you never edit a state value. You build a new one and hand it to the setter. It assumes you can read JavaScript objects, arrays, and the spread operator, and that you have written a function component with useState and an event handler.
The rule in one sentence
Any object or array you put in state is read-only from the component's point of view. To change what the screen shows, create a new object or array that has the values you want, and pass it to the setter function.
The earlier chapters explained why: each render sees a snapshot of state, and React decides whether to re-render by comparing the value you pass to the setter with the value it already holds. This chapter turns that into a working habit.
Primitives and objects behave differently
Numbers, strings, and booleans are already immutable in JavaScript. You cannot change the number 5 into 6. You can only replace it, so state with primitives follows the rule automatically.
const [count, setCount] = useState(0);
setCount(count + 1); // a new number replaces the old oneObjects and arrays are different. JavaScript lets you change their contents while keeping the same identity, so the language does not stop you from breaking the rule. The mistake is easy to make and the code looks natural:
import { useState } from 'react';
export default function Profile() {
const [person, setPerson] = useState({ firstName: 'Ada', lastName: 'Lovelace' });
function handleFirstNameChange(e) {
// Wrong: this edits the object that is already in state.
person.firstName = e.target.value;
setPerson(person);
}
return (
<label>
First name:
<input value={person.firstName} onChange={handleFirstNameChange} />
</label>
);
}Typing into this input appears to do nothing. The setter receives the same object reference that state already holds. React compares the old and new values with Object.is, finds them equal, and skips the re-render. The object was edited, but nothing told the screen to redraw.
Same reference or new reference
The distinction that matters is identity, not content. Two objects with identical fields are still different values if they are separate objects.
const a = { n: 1 };
const b = a; // same object
const c = { ...a }; // new object, same contents
console.log(Object.is(a, b)); // true
console.log(Object.is(a, c)); // falseReact only sees a change when the reference differs. This is why replacing works and editing does not.
Replace, don't change
The corrected handler builds a new object. The spread operator copies every property of person into a fresh object, and the property listed after it overrides the one you want to change.
import { useState } from 'react';
export default function Profile() {
const [person, setPerson] = useState({ firstName: 'Ada', lastName: 'Lovelace' });
function handleFirstNameChange(e) {
setPerson({ ...person, firstName: e.target.value });
}
return (
<label>
First name:
<input value={person.firstName} onChange={handleFirstNameChange} />
<span> {person.firstName} {person.lastName}</span>
</label>
);
}Now the setter gets a different reference every time, React re-renders, and the new snapshot shows the typed text. The old object is untouched. Spread syntax and the object-specific details are the subject of the next chapter, so treat { ...person, firstName: ... } as a pattern for now.
What counts as mutation
Mutation is any operation that changes an existing object or array in place. These are the common forms:
| Mutation (avoid on state) | Replacement (use instead) |
|---|---|
| `person.age = 30` | `{ ...person, age: 30 }` |
| `delete person.nickname` | Build a new object without that key |
| `items.push(x)` | `[...items, x]` |
| `items[2] = x` | `items.map(...)` with a replaced item |
| `items.splice(i, 1)` | `items.filter(...)` |
| `items.sort()` | Copy first, then sort the copy |
The middle column is only a quick list of what to avoid. The array and object chapters that follow cover each replacement in detail.
Local mutation is fine
The rule applies to values that React already holds in state. An object you create during the current render and have not yet passed to the setter belongs to you, and changing it is harmless.
function handleAddTag(tag) {
const next = [...tags]; // a fresh array nobody else has seen
next.push(tag); // mutating your own copy is fine
setTags(next); // the finished copy replaces the state
}This is the same idea as the sorting example later in the tutorial: copy first, then use any method you like on the copy. What you must never do is mutate tags itself.
Why the shortcut fails in more places than the screen
Skipping the re-render is the most visible symptom, but it is not the only one.
- Stale or inconsistent renders. If you mutate an object and also trigger a re-render some other way, the component may show the new value while memoized children, effects, or comparisons still hold the old reference and behave as if nothing changed.
- Memoization breaks.
React.memo,useMemo, and dependency arrays compare by reference. A mutated object has the same reference, so these tools can skip work that should happen. - Lost history. Each snapshot is a separate value. If you mutate, the previous snapshot no longer exists, so features such as undo or "compare with previous" have nothing to look at.
- Hard-to-trace bugs. Several components can hold the same object. Mutating it changes what all of them see, at times that React did not choose.
Treating state as read-only avoids all four with one habit.
Common errors
- Mutating and then calling the setter with the same object. This is the example at the top of the chapter. The fix is to pass a new object.
- Assuming a copy is deep. Spread copies one level. If
personholds a nestedaddressobject,{ ...person }shares thataddresswith the old state. Editingcopy.address.citystill mutates state. The nested-objects chapter handles this. - Reassigning the state variable. Writing
person = { ...person, firstName: 'Grace' }changes only the local variable for this render. React never hears about it. Only the setter updates state. - Using a mutating array method on the copy of a reference.
const next = items; next.push(x); setItems(next);does not copy anything.nextanditemsare the same array. - Calling the setter and then reading state. After
setPerson(...),personin the same handler still holds the old snapshot. Use the value you just built if you need it.
function handleReset() {
const next = { ...person, firstName: '' };
setPerson(next);
console.log(person.firstName); // still the old value
console.log(next.firstName); // ''
}Making the rule enforceable
Because JavaScript will not stop you, a few habits help.
- Write the new value as an expression inside the setter call, such as
setPerson({ ...person, ... }), so there is no named variable pointing at the old object to mutate by mistake. - In code review, search handlers for assignments to state fields (
state.x =) and forpush,splice,pop,shift,unshift,sort, andreversecalled on state. - Optionally, freeze values in development with
Object.freezewhile debugging. In strict mode, writing to a frozen object throws an error instead of failing quietly.
'use strict';
const person = Object.freeze({ firstName: 'Ada', lastName: 'Lovelace' });
try {
person.firstName = 'Grace';
} catch (err) {
console.log(err instanceof TypeError); // true
}Object.freeze is shallow, like spread, so it protects only the top level. It is a debugging aid, not a replacement for the habit.
Is copying expensive?
A common worry is that building a new object on every change wastes memory and time. For typical UI state it does not. A shallow copy duplicates only the top-level references, not the data they point to, so the cost is proportional to the number of fields or items in that one object or array. Nested values that you did not change are shared between the old and new versions. That sharing is also what lets reference comparisons detect exactly which parts changed.
If you later hold very large arrays that change many times per second, measure before optimizing. The final chapters cover keeping state flat and using Immer, which reduces boilerplate without changing the rule.
Summary of the working model
- State values are snapshots. Do not edit them.
- To change an object or array, build a new one and pass it to the setter.
- React detects change by reference, so a new reference triggers a render and the same reference does not.
- Copy first, then mutate freely, if you need a mutating method such as
sort. - Spread is shallow. Nested data needs its own copy at each level you change.
Exercise
A component keeps const [cart, setCart] = useState({ owner: 'Sam', total: 0 }). A teammate writes function addTen() { cart.total = cart.total + 10; setCart(cart); } and reports that the displayed total never changes. Explain why, and write the corrected function.
Show answer
The code edits the object that is already in state and then passes the same reference to setCart. React compares the old and new values with Object.is, sees the same reference, and skips the re-render. The corrected version creates a new object: function addTen() { setCart({ ...cart, total: cart.total + 10 }); }. The spread copies owner, and the later total property overrides the old total.
Exercise
Which of these lines is safe to run inside an event handler when items is state, and why? (a) items.push(4); setItems(items); (b) const next = [...items]; next.push(4); setItems(next); (c) setItems(items.concat(4));
Show answer
(b) and (c) are safe. In (b) the spread creates a new array, so push changes only your own copy and setItems receives a new reference. In (c) concat does not mutate and returns a new array. (a) mutates the array in state and passes the same reference back, so React sees no change.