Sub topic 1
State is a snapshot, not a variable you edit
Prerequisites
This chapter assumes you know:
- JavaScript objects, arrays, and the spread operator.
- Array methods such as
map,filter, andslice. - How to write a basic React function component and call
useState. - How to handle events such as
onClickin React.
You don't need to know anything about updater functions or Immer yet. Later chapters cover both.
Why this chapter comes first
Every pattern in this tutorial, such as spreading objects, filtering arrays, or mapping over items, follows from one idea. React state behaves like a snapshot of your data taken at the moment a render starts. It does not behave like a variable you edit in place. Once you see this, the rule "don't mutate state" stops being a style preference and becomes something you can predict.
A render is a photograph
When React renders a component, it calls your function. Inside that call, useState returns the state value for that render. Your JSX, your event handlers, and every variable in the function all see that same value until the next render.
Calling a setter such as setCount doesn't change the variable in the current function call. It asks React to schedule a new render with a new value. React then calls your component function again, and that call gets a fresh snapshot.
The note in the diagram is the point of the chapter. After setCount(1) runs, the handler that called it still sees count as 0, because that handler belongs to Render 1.
Setting state doesn't change the running code
Here is a small component that shows the effect.
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log('Right after setCount:', count);
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}On the first click, the screen changes to "Clicked 1 times". The console prints Right after setCount: 0. The log runs in the same function call that read count as 0, and that value can't change. Only the next render sees 1.
Three calls, one result
The same rule explains a common surprise. What do you expect this button to do?
import { useState } from 'react';
export default function TripleCounter() {
const [number, setNumber] = useState(0);
return (
<>
<h1>{number}</h1>
<button
onClick={() => {
setNumber(number + 1);
setNumber(number + 1);
setNumber(number + 1);
}}
>
+3
</button>
</>
);
}The numberes up by 1, not 3. In this render number is 0, so each line is effectively setNumber(0 + 1). React receives three requests that all say "set it to 1", and the final value is 1.
If you replaced each number with its snapshot value, the handler would look like this:
setNumber(0 + 1);
setNumber(0 + 1);
setNumber(0 + 1);When a new value depends on the previous one, there is a form of the setter that handles it. The chapter on updater functions covers it. For now, the point is that a plain value passed to a setter is computed from the snapshot.
Handlers keep the snapshot they were created with
A handler is created during a render and closes over that render's values. If the handler runs later, it still uses the old snapshot, even if the state has changed in the meantime.
import { useState } from 'react';
export default function DelayedAlert() {
const [number, setNumber] = useState(0);
return (
<>
<h1>{number}</h1>
<button
onClick={() => {
setNumber(number + 5);
setTimeout(() => {
alert(number);
}, 3000);
}}
>
+5
</button>
</>
);
}Click the button once. The heading changes to 5 right away. Three seconds later the alert shows 0, not 5. The timeout callback was created in the render where number was 0, and it keeps that value for as long as it lives.
This is a strength of the model. A handler always works with consistent data. It can't see half of one update and half of another. The same property is why you can reason about a handler by reading the code of a single render.
State is not a regular variable
Two other approaches look like they should work, and they show why useState exists.
A local variable doesn't survive between renders, because every render of the function creates a new one. A change to it also doesn't tell React to render again.
import { useState } from 'react';
export default function BrokenCounter() {
let count = 0; // recreated as 0 on every render
function handleClick() {
count = count + 1; // changes a variable React doesn't watch
console.log(count);
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}The console logs 1, but the screen stays at "Clicked 0 times". Nothing asked React to render again, and even if something had, count would be reset to 0.
useState fixes both problems:
- It keeps the value between renders, so the next render gets the stored value instead of a fresh
0. - Its setter tells React that something changed and a new render is needed.
Where mutation fits in
Objects and arrays make the snapshot idea trickier. Look at this code, which assumes person is an object in state:
person.firstName = 'Grace';This does change the object that sits inside the current snapshot, because JavaScript objects are shared by reference. But nothing has told React to render. The component function doesn't run again, so the screen keeps showing the old name. If another update causes a render later, the mutated value may suddenly appear. That makes the bug appear to come and go, which is harder to debug than a bug that always fails.
The snapshot model gives you a clear rule. A snapshot should not change once it exists. To change something, you build a new value and pass it to the setter. Then React renders again with a new snapshot.
What changes and what doesn't
| Question | Answer |
|---|---|
| Does calling a setter change the variable in the current function call? | No. The variable keeps its value for that render. |
| When does the new value appear? | In the next render, which React schedules after your handler finishes. |
| Does an older handler see newer state? | No. It keeps the snapshot from the render that created it. |
| Does editing a local variable update the screen? | No. React doesn't know about it, and the variable resets on the next render. |
| Does mutating an object in state update the screen? | Not reliably. React isn't told to render, and the next snapshot isn't a new value. |
Here is that advice in code:
import { useState } from 'react';
export default function Greeting() {
const [name, setName] = useState('Ada');
function handleChange(e) {
const nextName = e.target.value;
setName(nextName);
console.log('New name:', nextName); // correct, unlike logging `name`
}
return <input value={name} onChange={handleChange} />;
}How this sets up the rest of the tutorial
The following chapters rely on this model:
- Mutating an object leaves React with no signal and no new value, so we first look at what goes wrong.
- Replacing state with a copy gives React both a signal and a new snapshot. For objects, that means the spread operator. For arrays, it means non-mutating methods like
filterandmap. - Because snapshots hold fixed values, updates that depend on earlier updates need a different form of setter.
Keep the photograph picture in mind. You never edit a photograph. You take a new one.
Exercise
A component has const [score, setScore] = useState(10);. A click handler runs setScore(score + 1); setScore(score + 1); console.log(score);. What does the console print, and what is score on the screen after the next render?
Show answer
The console prints 10, because the handler reads the snapshot from the render that created it, and calling a setter doesn't change score in that call. Both setter calls pass 10 + 1, so they both request 11. After the next render the screen shows 11, not 12.
Exercise
A handler calls setName('Grace') and then immediately calls alert(name). Why does the alert show the old name, and how would you show the new one?
Show answer
name is part of the snapshot for the current render, and that value stays the same until the next render. To show the new name, store it in a local variable first, for example const next = 'Grace'; setName(next); alert(next);.