Sub topic 13
Remembering values with useState
What this chapter assumes
You should already be comfortable with function components, props, JSX expressions in curly braces, and event handlers such as onClick. You should also know JavaScript destructuring, the spread operator, and the difference between mutating and copying an object or array.
By the end you will be able to add state to a component, predict when and how it updates, and avoid the usual mistakes with updates, objects, and arrays.
Why a plain variable is not enough
A component is a function. React calls it every time it needs to know what the component should show. Each call starts with fresh local variables. A change to a local variable is lost on the next call, and React does not know the change happened, so it does not call the function again.
function BrokenCounter() {
let count = 0;
function handleClick() {
count = count + 1;
console.log(count);
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}The console logs 1, 2, 3, but the button always says "Clicked 0 times". Two things are missing: a place to keep a value between calls, and a way to tell React to call the component again. useState supplies both.
The useState call
useState is a Hook, a function that lets a component use a React feature. It takes an initial value and 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 names are your choice. The convention is [thing, setThing]. Array destructuring is used because it lets you name the pair yourself.
The initial value is used only on the first render. On later renders React ignores the argument and returns the stored value. React keeps that stored value outside your function, attached to this component's position in the tree.
What happens when you call the setter
Calling setCount(1) does not change count in the running function. It asks React to store a new value and render the component again. During that new render, useState returns the new value.
React compares the new JSX with the previous JSX and changes only the parts of the page that differ. If the new value is identical to the old one (compared with Object.is), React skips the update.
State is a snapshot
Each render has its own fixed values for state, props, and handlers. The count inside a given render never changes, even after you call the setter. This surprises many people:
import { useState } from 'react';
function Snapshot() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
console.log(count); // still the value from this render
}
return <button onClick={handleClick}>Count: {count}</button>;
}On the first click, count is 0 in all three lines, so you ask React three times to set the value to 1. The result is 1, not 3. The console.log prints 0.
Updater functions
When the next value depends on the previous one, pass a function to the setter. React queues these functions and runs them in order, each receiving the result of the one before.
import { useState } from 'react';
function TripleCounter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount((c) => c + 1);
setCount((c) => c + 1);
setCount((c) => c + 1);
}
return <button onClick={handleClick}>Count: {count}</button>;
}Now one click adds 3. A common habit is to name the parameter after the state, for example (count) => count + 1, or to use its first letter.
Use an updater whenever the new value is computed from the old one. Use a plain value when it does not depend on the old one, such as setOpen(false).
React batches updates from one event. It runs your handler to the end, then renders once. That is why three setter calls cause one render, not three.
Objects and arrays: replace, don't mutate
React decides whether state changed by comparing the old and new values with Object.is. For objects and arrays, that compares references. If you mutate an object and pass the same reference back, React sees no change and may skip the render.
Treat state as read-only. To change it, build a new object or array and pass that to the setter.
import { useState } from 'react';
function SignupForm() {
const [form, setForm] = useState({ name: '', email: '' });
function handleChange(event) {
const { name, value } = event.target;
setForm((prev) => ({ ...prev, [name]: value }));
}
return (
<form>
<input name="name" value={form.name} onChange={handleChange} />
<input name="email" value={form.email} onChange={handleChange} />
<p>
{form.name} <{form.email}>
</p>
</form>
);
}The spread copies the old fields into a new object. The computed key [name] then overwrites one field. Two details matter here. The setter replaces state completely and does not merge it, so without ...prev you would lose email when typing a name. Also, the code reads event.target before calling the setter, so the updater does not depend on the event object.
Arrays follow the same rule. Avoid push, splice, and assigning by index. Use [...items, newItem], filter, and map instead.
import { useState } from 'react';
function TodoApp() {
const [todos, setTodos] = useState([]);
const [text, setText] = useState('');
function addTodo() {
if (text.trim() === '') return;
setTodos((prev) => [...prev, { id: crypto.randomUUID(), text, done: false }]);
setText('');
}
function toggleTodo(id) {
setTodos((prev) =>
prev.map((todo) => (todo.id === id ? { ...todo, done: !todo.done } : todo))
);
}
function removeTodo(id) {
setTodos((prev) => prev.filter((todo) => todo.id !== id));
}
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={addTodo}>Add</button>
<ul>
{todos.map((todo) => (
<li key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => toggleTodo(todo.id)}
/>
{todo.text}
</label>
<button onClick={() => removeTodo(todo.id)}>Remove</button>
</li>
))}
</ul>
</div>
);
}Note the two useState calls. A component can have as many state variables as it needs. Prefer several small ones for unrelated values, and group values in one object only when they usually change together.
The id is created when the item is added, not during rendering. That keeps the keys stable, as the earlier chapter on lists required.
Each component instance has its own state
State belongs to one place in the tree, not to the component definition. Rendering <Counter /> twice creates two independent counters.
export default function App() {
return (
<>
<Counter />
<Counter />
</>
);
}React matches state to a component by its position and type in the tree. If a component is removed from the tree, its state is discarded. If it is rendered again later, it starts from the initial value. The key prop can force this reset: changing the key of a component makes React treat it as a new instance.
Initial values that are expensive to compute
The argument to useState is evaluated on every render, even though only the first one uses it. If computing it is costly, pass a function. React calls it once, on the first render.
import { useState } from 'react';
function buildInitialItems() {
return Array.from({ length: 1000 }, (_, i) => `Item ${i + 1}`);
}
function ItemPicker() {
const [items] = useState(buildInitialItems); // pass the function, do not call it
const [selected, setSelected] = useState(null);
return (
<ul>
{items.slice(0, 5).map((item) => (
<li key={item}>
<button onClick={() => setSelected(item)}>{item}</button>
</li>
))}
<li>Selected: {selected ?? 'none'}</li>
</ul>
);
}Writing useState(buildInitialItems()) would still work but would rebuild the list on every render and throw it away.
Rules for Hooks
React tracks state by the order of useState calls in each render. For that to work:
- Call Hooks only at the top level of a component. Never call them inside conditions, loops, or nested functions.
- Call Hooks only from function components or from your own custom Hooks, which are functions whose names start with
use.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Value is one step behind after calling the setter | You read the variable in the same handler and it still holds the old snapshot | Compute the next value in a local variable, use it, and pass it to the setter |
| Several increments in one handler add only 1 | Each call used the same stale value | Use an updater: `setCount((c) => c + 1)` |
| Screen does not change after editing an object or array | You mutated state and passed the same reference | Create a copy with spread, `map`, or `filter` |
| Other fields vanish after an update | The setter replaces state and does not merge | Spread the previous object: `{ ...prev, field }` |
| "Too many re-renders" | The setter is called during rendering, or `onClick={fn()}` calls it immediately | Pass a function: `onClick={() => setX(1)}` |
| State resets unexpectedly | The component was unmounted, or its key or position changed | Keep the component in the same place, or move the state to a parent |
Choosing what to put in state
Store only values that change over time and that affect what the screen shows. If a value can be calculated from props or other state, calculate it during rendering. For example, keep todos in state and compute const remaining = todos.filter((t) => !t.done).length in the component body. Duplicated state drifts out of sync.
If two components need the same value, move the state to their closest common parent and pass it down as props, with a setter-calling function for the child to use.
Exercise
A component has const [count, setCount] = useState(0); and a handler that runs setCount(count + 5); setCount((c) => c * 2);. What is count on the next render after one click, and what would it be if the second call were setCount(count * 2) instead?
Show answer
With the updater, React queues "set to 5" and then applies c => c * 2 to 5, so the result is 10. With setCount(count * 2), the second call uses the snapshot value 0 and sets the state to 0. It replaces the queued 5, so the final value is 0.
Exercise
This handler is meant to mark one user as active, but the screen does not update. Explain why and write the fix. function activate(id) { const user = users.find((u) => u.id === id); user.active = true; setUsers(users); }
Show answer
The code mutates the existing user object and passes the same array reference to setUsers. React compares references, sees no change, and skips the render. Fix it by building new values: setUsers((prev) => prev.map((u) => (u.id === id ? { ...u, active: true } : u)));