Events give your components a way to hear the user. State gives them a way to remember what happened. You built the mechanism in Hooks from scratch: a useState that stores its value in a slot on the fiber, a setter that queues an update and schedules a re-render, and a cursor that matches each call to its slot by order.
Real useState works the same way, and almost every confusing thing about it follows from that design. A state variable is a constant inside each render. Setting it doesn't change it; it asks for a new render. Updates are queued and batched. And the memory belongs to a position in the tree, not to your function. This is the most asked-about hook in interviews, so we'll go slowly, and at the end we'll start the reading list app that the rest of the guide grows.
The problem: a variable that forgets#
Why not just use a variable?
export default function App() {
let count = 0;
return (
<button
onClick={() => {
count = count + 1;
console.log("count is now", count);
}}
>
Clicked {count} times
</button>
);
}The console counts up, the button stays at 0. Two things are missing. Changing a local variable doesn't tell React to render again. And even if something else caused a render, App would run from the top and let count = 0 would reset it. You need memory that survives between calls and a way to request a render. That's useState:
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}The essentials of the API:
useState(initial)returns a pair: the current value and a setter. The initial value is only used on the first render; after that React returns what it has stored.- Lazy initialization:
useState(() => readFromStorage())takes a function, and React calls it only on the first render.useState(readFromStorage())would call it on every render and throw the result away. - The setter is stable. Its identity never changes between renders, so it's safe to leave out of dependency lists.
- Same value, no work. If the new value is the same as the current one by
Object.is, React bails out and skips re-rendering that component's children (it may still call the component once to be sure). - Typing pattern: TypeScript infers the type from the initial value. When the initial value doesn't describe every possible value, pass the type:
useState<Book | null>(null),useState<string[]>([]).
State is a snapshot#
Here's the question interviewers love. What does the button show after one click?
Predict the number after one click. Then run it.
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
return (
<>
<h2>{count}</h2>
<button
onClick={() => {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
}}
>
+3?
</button>
</>
);
}Every render is a function call, and count is a const in that call. The JSX, the event handlers, anything created during that render sees the value it had at that moment. Calling setCount doesn't reach into the current render and change the variable. It queues an update for the next render. So it's useful to think of each render as taking a snapshot: props, state and the handlers closed over them, frozen together.
Render 1. React calls Counter with count = 0. Everything created in this render, the JSX and the click handler, sees count as the constant 0. That's the snapshot.
This maps directly onto your toy. The setter pushed an update onto the hook's queue and scheduled a render; the next call to useState processed the queue against the stored value. Nothing in that design could change a const that already exists.
Updater functions#
When the next state depends on the previous one, pass a function instead of a value:
setCount((c) => c + 1);
setCount((c) => c + 1);
setCount((c) => c + 1); // 3 after one clickAn updater says "take whatever the state is by the time you get to me, and do this to it". React runs the queue in order, feeding each updater the result of the one before. You can mix the two forms: a plain value means "replace with this", an updater means "transform the pending value".
`number` is 0. A handler calls `setNumber(number + 5)` and then `setNumber(n => n + 1)`. What's the next render's value?
Updaters run during the next render, so they must be pure: no side effects, no reading mutable outside values. StrictMode calls them twice in development to check (see Components and props). A common naming convention is the first letter of the state (c for count) or prev.
Do you need the updater every time? No. If you're setting a value that doesn't depend on the old one (setName(e.target.value)), a value is clearer. Reach for an updater when the update depends on the previous state, especially when several updates can queue up before a render, or when the code runs later (a timer, a promise) and the snapshot might be old.
Automatic batching#
React doesn't render after every setter call. It waits until your code is done, then renders once with all queued updates. That's batching. Before React 18, React only batched inside its own event handlers; updates in a setTimeout, a promise or a native listener rendered one at a time. Since React 18 and createRoot, batching is automatic everywhere.
import { useState } from "react";
import { flushSync } from "react-dom";
import { Rendered } from "guide-tools";
export default function App() {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
return (
<Rendered label="App">
<p>a = {a}, b = {b}</p>
<button
onClick={() => {
setTimeout(() => {
setA((x) => x + 1);
setB((x) => x + 1); // one render for both
}, 0);
}}
>
Two updates in a timeout
</button>{" "}
<button
onClick={() => {
flushSync(() => setA((x) => x + 1)); // renders right now
setB((x) => x + 1); // second render
}}
>
flushSync
</button>
</Rendered>
);
}The first button adds one to the render count per click, even though two pieces of state changed outside a React event. The second adds two, because flushSync forces React to render and commit its update immediately. You almost never need flushSync. The legitimate case is when the very next line has to read the DOM after the update, like scrolling to an item you just added. It's slow by design: it throws away the batching that makes React fast.
Batching is why you can't "see" state change inside a handler, and it's also why reading the DOM right after setState gives you the old DOM. Both are the same fact: rendering happens after your code returns.
Stale closures#
A snapshot doesn't expire when the render ends. Any function created during that render, including callbacks that run much later, keeps seeing that render's values. Type a message, press Send, then change the text before the alert appears:
import { useState } from "react";
export default function App() {
const [to, setTo] = useState("Ada");
const [message, setMessage] = useState("Hello");
function handleSend() {
setTimeout(() => {
alert(`You said "${message}" to ${to}`);
}, 3000);
}
return (
<>
<label>
To:{" "}
<select value={to} onChange={(e) => setTo(e.target.value)}>
<option>Ada</option>
<option>Linus</option>
</select>
</label>
<br />
<input value={message} onChange={(e) => setMessage(e.target.value)} />
<button onClick={handleSend}>Send</button>
</>
);
}The alert shows what you'd sent, not what the inputs say three seconds later. Here that's the right behavior: you clicked Send to Ada, so a later change of recipient shouldn't redirect the message. The closure is "stale" only when you wanted the latest value. Then you have two tools:
- For updates, use an updater.
setCount(c => c + 1)inside a timer never reads the stalecount. - For reads, keep the latest value in a ref, a mutable box that isn't part of the snapshot. That's in Refs. Stale closures inside effects get their own treatment in Effects.
Updating objects and arrays immutably#
State can hold any value, including objects and arrays. The rule: treat state as read-only. To change it, create a new value and set that.
const [book, setBook] = useState({ title: "Refactoring", meta: { year: 1999, tags: ["craft"] } });
// Wrong: mutates the object React already has, then sets the same reference.
book.meta.year = 2018;
setBook(book); // Object.is(old, new) is true, so React bails out. No render.
// Right: copy along the path you change.
setBook({ ...book, meta: { ...book.meta, year: 2018 } });Why so strict? Three reasons, all mechanical:
- Bail-outs compare references. React decides whether anything changed with
Object.is. A mutated object is the same object, so it looks unchanged. - Snapshots must stay frozen. A previous render's handlers, a pending transition, or a memoized child all hold references to old state. Mutating it rewrites the past under them.
- Memoization depends on it.
memo,useMemoand the React Compiler skip work when inputs are the same reference. Mutation makes them show stale data (Memoization).
For arrays, prefer the methods that return a new array:
| Goal | Avoid (mutates) | Use (new array) |
|---|---|---|
| Add | push, unshift | [...arr, item], [item, ...arr] |
| Remove | splice, pop, shift | filter |
| Replace or update an item | arr[i] = x | map returning a new item where it matches |
| Sort or reverse | sort, reverse | toSorted, toReversed, or copy first |
| Insert at index | splice | [...arr.slice(0, i), x, ...arr.slice(i)] or toSpliced |
Updating one item inside an array means making a new array and a new object for the item you change. The other items can be reused as they are:
setItems(items.map((it) => (it.id === id ? { ...it, read: !it.read } : it)));Deeply nested updates get noisy fast. Immer lets you write the mutation and produces the immutable copy for you. Its produce function, called with only a recipe, returns an updater you can pass straight to the setter:
import { produce } from "immer";
setBook(
produce((draft) => {
draft.meta.year = 2018; // looks like a mutation; Immer records it on a draft
draft.meta.tags.push("classic");
}),
);Immer works by handing your recipe a proxy, recording what you change, and building a new object that shares every untouched branch with the old one. We'll use it with reducers in useReducer.
The reading list, part 1#
Time to start the app that runs through the rest of the guide: a reading list over the books fixture, where each entry has a local read flag. This version lists books, adds one and toggles read, all with useState and immutable updates.
import { useState } from "react";
import { books } from "guide-tools";
type Book = (typeof books)[number];
type Entry = Book & { read: boolean };
let nextId = 1000;
export default function ReadingList() {
const [entries, setEntries] = useState<Entry[]>(() =>
books.slice(0, 3).map((b) => ({ ...b, read: false })),
);
const [title, setTitle] = useState("");
// Derived, not stored: computed from entries on every render.
const unread = entries.filter((e) => !e.read).length;
function handleAdd() {
const t = title.trim();
if (!t) return;
setEntries([...entries, { id: nextId++, title: t, author: "Unknown", year: 2026, tags: [], read: false }]);
setTitle("");
}
function handleToggle(id: number) {
setEntries(entries.map((e) => (e.id === id ? { ...e, read: !e.read } : e)));
}
return (
<>
<h3>Reading list ({unread} unread)</h3>
<ul style={{ listStyle: "none", padding: 0 }}>
{entries.map((e) => (
<li key={e.id}>
<label style={{ textDecoration: e.read ? "line-through" : "none" }}>
<input type="checkbox" checked={e.read} onChange={() => handleToggle(e.id)} /> {e.title}
</label>
</li>
))}
</ul>
<form
onSubmit={(e) => {
e.preventDefault();
handleAdd();
}}
>
<input aria-label="New book" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Add a book" />
<button>Add</button>
</form>
</>
);
}Notice what isn't state: unread. It's computed from entries on every render. That's the first rule of the next section.
Someone wrote the reading list with mutations. Toggling a book does nothing on screen. Adding one seems to work, but it's the same bug in disguise. Fix both handlers without changing the JSX.
import { useState } from "react";
import { books } from "guide-tools";
type Entry = (typeof books)[number] & { read: boolean };
let nextId = 1000;
export default function ReadingList() {
const [entries, setEntries] = useState<Entry[]>(() => books.slice(0, 3).map((b) => ({ ...b, read: false })));
const [title, setTitle] = useState("");
const unread = entries.filter((e) => !e.read).length;
function handleAdd() {
if (!title.trim()) return;
entries.push({ id: nextId++, title: title.trim(), author: "Unknown", year: 2026, tags: [], read: false });
setEntries(entries);
setTitle("");
}
function handleToggle(id: number) {
const entry = entries.find((e) => e.id === id)!;
entry.read = !entry.read;
setEntries(entries);
}
return (
<>
<h3>{unread} unread</h3>
<ul>
{entries.map((e) => (
<li key={e.id}>
<label>
<input type="checkbox" checked={e.read} onChange={() => handleToggle(e.id)} />
{e.title}
</label>
</li>
))}
</ul>
<form
onSubmit={(e) => {
e.preventDefault();
handleAdd();
}}
>
<input aria-label="New book" value={title} onChange={(e) => setTitle(e.target.value)} />
<button>Add</button>
</form>
</>
);
}Structuring state#
Most state bugs aren't about the API. They're about choosing what to store. A few principles cover most of them:
- Don't store what you can compute. If a value can be derived from props or other state during render, derive it.
unreadabove,fullNamefromfirstandlast, a filtered list from the list and the query. Stored derived values have to be kept in sync by hand, which is the bug from The DOM and the sync problem all over again. - Don't duplicate. Store an id, not a copy of the object. A copied object goes stale the moment the original is edited.
- Group what changes together. If two values always update at the same time (
xandyof a pointer), one object is simpler than two calls that must stay in step. - Avoid contradictions.
isSendingandisSentcan both be true by mistake. Onestatus: "typing" | "sending" | "sent"can't. (This idea grows into state machines in State machines.) - Avoid deep nesting. Normalized, flat data (items by id) makes immutable updates much shorter.
- Don't mirror props in state unless you mean "initial value".
useState(props.color)reads the prop once; later changes are ignored. Name itinitialColorwhen that's the intent.
If the derived computation is expensive, memoize it with useMemo (Memoization) rather than storing it.
The Details panel shows the selected book. Select a book, then toggle its checkbox: the list updates, but the panel still says it's unread. Fix the state structure.
import { useState } from "react";
import { books } from "guide-tools";
type Entry = (typeof books)[number] & { read: boolean };
export default function App() {
const [entries, setEntries] = useState<Entry[]>(() => books.slice(0, 3).map((b) => ({ ...b, read: false })));
const [selected, setSelected] = useState<Entry | null>(null);
function handleToggle(id: number) {
setEntries(entries.map((e) => (e.id === id ? { ...e, read: !e.read } : e)));
}
return (
<>
<ul>
{entries.map((e) => (
<li key={e.id}>
<label>
<input type="checkbox" checked={e.read} onChange={() => handleToggle(e.id)} />
{e.title}
</label>{" "}
<button onClick={() => setSelected(e)}>Details</button>
</li>
))}
</ul>
<section>
<h4>Details</h4>
{selected ? (
<p data-details>
{selected.title}: {selected.read ? "read" : "unread"}
</p>
) : (
<p>Nothing selected</p>
)}
</section>
</>
);
}Lifting state up#
When two components need the same state, move it to their closest common parent and pass it down. The parent owns the data; children get values and callbacks as props. That's "lifting state up", and it's how React keeps one source of truth without any library.
Here's the reading list split into components. The header needs the unread count, the list needs entries and a toggle, the form needs to add. So entries lives in ReadingList. The draft title, which only the form cares about, stays in the form.
function ReadingList() {
const [entries, setEntries] = useState<Entry[]>(initialEntries);
const unread = entries.filter((e) => !e.read).length;
return (
<>
<Header unread={unread} />
<BookList
entries={entries}
onToggle={(id) => setEntries(entries.map((e) => (e.id === id ? { ...e, read: !e.read } : e)))}
/>
<AddBook onAdd={(title) => setEntries([...entries, makeEntry(title)])} />
</>
);
}
function AddBook({ onAdd }: { onAdd: (title: string) => void }) {
const [title, setTitle] = useState(""); // local: nobody else needs the draft
// ...
}Keep state as low as it can go and as high as it must. Lifting too high means every keystroke in a form re-renders a whole page; too low means siblings can't agree. When lifting starts to mean passing props through many layers that don't use them, look at composition first, then context (Context).
State belongs to a position in the tree#
Here's the part of the mechanism that surprises people. In your toy, hook slots lived on the fiber, and the fiber was matched to elements by type and key at each position. Real React works the same way. State isn't inside the component function or the element; it's attached to the place in the tree where that component renders.
React doesn't store state inside your function. It stores it on the fiber at a position in the tree: "the first child of the div inside App". This Counter has been clicked three times.
That gives you two rules you can predict with:
- Same component type at the same position: state is preserved. Props can change completely; the state stays.
- Different type at that position, or a different key: state is destroyed. The old subtree unmounts (with all state below it), and the new one starts fresh.
Usually this is what you want. Sometimes it isn't, like when one component is reused for different "things".
Click Add one three times for Taylor, then click Next player. What score does Sarah start with? Then put key={isPlayerA ? "Taylor" : "Sarah"} on the Counter and try again.
import { useState } from "react";
function Counter({ person }: { person: string }) {
const [score, setScore] = useState(0);
return (
<div>
<h3>
{person}'s score: {score}
</h3>
<button onClick={() => setScore(score + 1)}>Add one</button>
</div>
);
}
export default function App() {
const [isPlayerA, setIsPlayerA] = useState(true);
return (
<div>
{isPlayerA ? <Counter person="Taylor" /> : <Counter person="Sarah" />}
<button onClick={() => setIsPlayerA(!isPlayerA)}>Next player</button>
</div>
);
}Resetting with a key is the clean answer to "this form should start fresh when the user switches to a different contact": <EditContact key={contact.id} contact={contact} />. No effect, no manual reset code. The opposite trap is the one from Components and props: a component defined inside another gets a new type every render, so its state resets every render.
Pitfalls#
Check your understanding#
An interviewer shows you three setCount(count + 1) calls in one handler and asks: "Why does this only add one, and what would you change?"
Interview angle
useState stores a value on the component's fiber and gives you a setter. Inside one render, state is a constant snapshot: the JSX and every handler created in that render see the same value, so calling the setter doesn't change the variable, it queues an update for the next render. React batches all updates into one render, everywhere since React 18. When the next value depends on the previous one, use an updater function. Treat state as immutable, because React compares references. Store the minimum and derive the rest, lift shared state up, and remember that state belongs to a position in the tree: change the type or key there and it resets.
A handler calls setCount(count + 1) three times. What happens, and why?
What is automatic batching, and what changed in React 18?
What's a stale closure in React, and how do you avoid one?
Why must state be updated immutably in React?
How do you decide what belongs in state?
What decides whether a component's state is preserved or reset across renders?
Recap#
useStatestores a value on the component's fiber and returns it with a stable setter. Lazy initializers run once; setting anObject.is-equal value bails out.- State is a snapshot: within one render it's a constant, and handlers and timers created in that render keep seeing it. Setting state queues an update for the next render.
- Use updater functions when the next state depends on the previous one. React batches all updates (everywhere since 18) into one render;
flushSyncopts out. - Treat state as immutable. Create new objects and arrays (or use Immer's
produce), because React, memoization and older snapshots all rely on references. - Store the minimum: derive what you can, store ids not copies, lift shared state to the closest common parent.
- State belongs to a position in the tree. Same type at the same position keeps it; a different type or key resets it.
Sources#
- react.dev: State: a component's memory, State as a snapshot, Queueing a series of state updates
- react.dev: Updating objects in state, Updating arrays in state
- react.dev: Choosing the state structure, Sharing state between components, Preserving and resetting state
- react.dev: useState, flushSync
- Immer: produce and curried producers
- Facts checked November 24, 2026.