Sub topic 13
Remembering values with useState
This chapter assumes you can write function components, pass props, embed expressions in JSX with curly braces, and attach an onClick handler. It adds the piece that lets a component remember something between renders.
Why a plain variable is not enough
A component is a function, and React calls it again every time it needs to render. A normal let variable inside it is recreated on each call. Changing that variable also doesn't tell React to update the screen.
State solves both problems. React stores the value outside your function and re-renders the component when you change it.
The useState hook
useState is a hook, a function that lets a component use a React feature. You call it with an initial value. It returns an array of two items: the current value and a setter function.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}The array destructuring lets you pick the names. The convention is thing and setThing. The initial value 0 is used only on the first render. Later renders ignore it and return the stored value.
What happens when you click
Each render sees a fixed snapshot of state. Inside one render, count never changes, even after you call setCount. The new value shows up on the next render.
Updating from the previous value
Because of the snapshot, this handler adds only 1:
function AddThree() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
}
return <button onClick={handleClick}>Count: {count}</button>;
}All three calls use the same count, so each one asks for the same next value. When the new value depends on the old one, pass an updater function. React queues the updaters and feeds each one the latest result.
setCount((c) => c + 1);
setCount((c) => c + 1);
setCount((c) => c + 1); // count ends up 3 higherState holds objects and arrays too
State can hold any value. For objects and arrays, always create a new one instead of changing the existing one.
import { useState } from 'react';
function NameForm() {
const [user, setUser] = useState({ name: 'Ada', age: 36 });
return (
<div>
<input
value={user.name}
onChange={(e) => setUser({ ...user, name: e.target.value })}
/>
<p>
{user.name} is {user.age}.
</p>
</div>
);
}The spread syntax ...user copies the existing fields, and name then overrides one of them.
Each instance has its own state
If you render <Counter /> twice, each copy keeps a separate count. State belongs to one component instance at its position in the tree. It is not shared through the function. To share a value, move it to a parent and pass it down as props.
Common errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| `onClick={setCount(1)}` | The setter runs during render, causing an endless loop | Pass a function: `onClick={() => setCount(1)}` |
| Reading state right after the setter | You still see the old value | Use the value in the next render, or compute it in a variable first |
| Mutating an object or array | No re-render | Copy with spread, `map`, or `filter` |
| Calling `useState` inside an `if` or loop | Hooks run in a different order and React breaks | Call hooks only at the top level of the component |
Exercise
A component has const [n, setN] = useState(5);. A click handler runs setN(n + 1); setN(n + 1);. What is n on the next render, and how do you change the handler so n becomes 7?
Show answer
n becomes 6, because both calls use the same snapshot value 5. Use updater functions instead: setN((x) => x + 1); setN((x) => x + 1);. React applies them in order, so the result is 7.