Chapter 7 Β· Adding Interactivity
State & Rendering
State is a component's memory. This chapter explains how it works and how React updates the screen when it changes.
- Why normal variables can't update the screen
- How to use
useState - The three steps of an update: trigger β render β commit
- Why state behaves like a snapshot
- How to queue several updates with updater functions
Why a normal variable isn't enough
Here's a gallery that tries to show the next sculpture when you click:
It doesn't work, for two reasons:
- Local variables don't survive between renders. On the next render,
Gallery()runs from scratch andlet index = 0starts over. - Changing a local variable doesn't trigger a render. React doesn't know anything changed.
To update the screen you need two things: keep the data between renders, and tell React to render again. useState gives you both.
Adding a state variable
useState returns an array of exactly two items, and the [a, b] syntax (array destructuring) names them. By convention, use [something, setSomething].
What happens on each click
Several state variables
A component can have as many as it needs:
State is private to each copy
If you render <Gallery /> twice, each copy gets its own index. Clicking one doesn't affect the other. State belongs to a specific component on screen, not to the function.
use are Hooks. Call them only at the top level of a component, never inside if, loops or nested functions. React tells your state variables apart by the order of the calls, so that order must never change between renders.
Render and commit: how the screen updates
Picture React as a kitchen: components are cooks and React is the waiter.
- Trigger: an order comes in. Either the app starts (the initial render via
createRoot().render()) or some state was updated with a setter. - Render: the cooks prepare the dish. React calls your component functions to find out what the screen should look like. On updates it calls the component whose state changed, and its children.
- Commit: the dish is served. React applies the minimal changes to the real DOM. If the output is the same as last time, React doesn't touch the DOM at all.
After the commit, the browser repaints the screen.
<input> survives a re-render of its parent.
State as a snapshot
This is the most surprising part for beginners. Look at this code:
You'd expect +3, but the number only goes up by 1. Why?
Each render has its own fixed copy of state, like a photo. In the render where number is 0, the click handler sees number = 0 the whole time:
A setter doesn't change the variable you already have. It asks React for a new render with the new value.
The snapshot even survives over time:
This is a feature: an event handler sees consistent values for the whole time it runs, so state can't change halfway through.
Queueing updates with updater functions
To update the same state several times in one event, pass a function that computes the next value from the previous one:
React puts the updates in a queue and processes them in order after your handler finishes:
| Queued update | n | returns |
|---|---|---|
n => n + 1 | 0 | 1 |
n => n + 1 | 1 | 2 |
n => n + 1 | 2 | 3 |
This is called batching. React waits until all the code in the event handler has run, then does one re-render with the final result. That's efficient, and you never see a half-updated screen.
setX(5)orsetX(value)when the new value doesn't depend on the old one.setX(x => x + 1),setOn(on => !on)when it depends on the previous value. It's always safe.- Name the parameter after the state's first letter (
n,c) orprev...(prevCount).
More examples
Example 1: a like button (boolean + number)
Example 2: controlled checkbox and select
For checkboxes, use checked and e.target.checked. For text, select and textarea, use value and e.target.value.
Example 3: a gallery with bounds
isFirst and isLast aren't state: they're calculated from index on every render.
Example 4: the snapshot in action
Example 5: a "render counter" with console.log
Recap
- Use state for data that changes and should update the screen:
const [x, setX] = useState(initial). - Calling a setter stores the new value and triggers a re-render.
- Updates go trigger β render (call components) β commit (minimal DOM changes).
- State is a snapshot: the variable keeps its value until the next render.
- Use
setX(prev => ...)to queue updates that build on each other. - Call Hooks only at the top level.
Exercises
1. A counter with + / β / reset
Show solution
2. Controlled input
Make an input whose text is stored in state, and show "Hello, {name}!" below it as you type. Hint: value={name} and onChange={e => setName(e.target.value)}.
Show solution
An input whose value comes from state is called a controlled input: React is the single source of truth for its text.
3. Predict the output
If number is 0, what's the next value?
Show answer
6. The queue is: "replace with 0 + 5 = 5", then "n => n + 1" β 6. And if the order were reversed (setNumber(n => n + 1) then setNumber(number + 5)), the answer would be 5, because the replacement comes last and wins.
4. Toggle a message π’ easy
Make a button labelled "Show details" or "Hide details" that toggles a paragraph on and off.
Show solution
5. Show/hide password π’ easy
Make a password input with a ποΈ button that switches its type between "password" and "text".
Show solution
6. Character counter π’ easy
Make a textarea with "42 / 100" shown below it. The counter turns red when the text is over 100 characters.
Show solution
7. Colour cycler π‘ medium
Make a box that cycles through ['red', 'orange', 'green', 'blue'] on each click, going back to the start after the last colour. Hint: (i + 1) % colors.length.
Show solution
8. Fix the +3 button π‘ medium
Show solution
Each call reads the same snapshot, so the result is only +1. Use updater functions: setScore(s => s + 1) three times, or simply setScore(score + 3).
9. A simple form with several fields π‘ medium
Make a form with first name, last name and age (a number input). Below it, show a live preview: "Asha Rao, 28 years old". Disable the Submit button until both names are filled in.
Show solution
Note Number(e.target.value): input values are always strings.
10. A mini quiz π΄ hard
Given an array of questions ({ q, options, answer }), show one question at a time with option buttons. Track the current question index and the score. After the last question, show "You scored 2 / 3" and a "Restart" button.
Show solution
π Official docs: State: A Component's Memory Β· Render and Commit Β· State as a Snapshot Β· Queueing State Updates