Sub topic 4
Updating state from event handlers
This chapter assumes you can write a function component, read JSX, pass props, and use arrow functions. You should also have seen useState return a value and a setter. Here you will learn how a user action reaches a setter, what React does with the call, and which mistakes cause the most bugs.
What an event handler is
An event handler is a function that React calls when something happens in the UI, such as a click, a key press, or a form submit. You attach it with a prop like onClick, onChange, or onSubmit. Prop names are camelCase, and the value is a function, not a string.
State changes mostly start in handlers. Rendering should only describe the UI for the current state. Handlers are where you respond to the user and request a new state.
import { useState } from 'react';
function LikeButton() {
const [liked, setLiked] = useState(false);
function handleClick() {
setLiked(!liked);
}
return (
<button onClick={handleClick}>
{liked ? 'Liked' : 'Like'}
</button>
);
}handleClick is defined inside the component, so it can read liked and call setLiked directly. React calls it when the user clicks. The setter asks React to re-render with a new value. It does not change liked in the running handler.
The path from click to screen
The setter call only queues an update. React re-renders after the handler returns. This is why code after a setter call still sees the old value, a topic the snapshot chapter covers in depth.
Pass the function, do not call it
The most common beginner error is calling the handler while writing the JSX.
import { useState } from 'react';
function Demo() {
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1);
}
return (
<>
<p>{count}</p>
{/* Correct: passes the function */}
<button onClick={increment}>Add</button>
{/* Correct: passes a new arrow function */}
<button onClick={() => setCount(count + 1)}>Add inline</button>
</>
);
}Compare these forms:
| JSX | What happens |
|---|---|
| `onClick={increment}` | React stores the function and calls it on click. |
| `onClick={() => increment()}` | React stores an arrow function that calls `increment` on click. |
| `onClick={increment()}` | `increment` runs during render, and its return value is passed as the handler. |
The third form is a bug. If increment calls a setter, you are updating state during render. That schedules another render, which calls increment again, and React stops with a "Too many re-renders" error.
Handlers that take arguments
You often need to tell a shared handler which item the user chose. Wrap the call in an arrow function so the call happens on click, not during render.
import { useState } from 'react';
const colors = ['red', 'green', 'blue'];
function ColorPicker() {
const [selected, setSelected] = useState('red');
function choose(color) {
setSelected(color);
}
return (
<>
<p>Selected: {selected}</p>
{colors.map(color => (
<button key={color} onClick={() => choose(color)}>
{color}
</button>
))}
</>
);
}Each button gets its own arrow function that closes over its own color. Creating a small function per item on each render is cheap. Do not optimize it until you have measured a problem.
The event object
React passes your handler an event object. It wraps the browser event and has the same shape in every browser. Common fields and methods:
e.targetis the element where the event started. In a change handler it is the input.e.currentTargetis the element the handler is attached to.e.preventDefault()stops the browser's default action, such as a form submit reloading the page.e.stopPropagation()stops the event from reaching parent handlers.
import { useState } from 'react';
function SignupForm() {
const [email, setEmail] = useState('');
const [submitted, setSubmitted] = useState(null);
function handleSubmit(e) {
e.preventDefault();
setSubmitted(email);
setEmail('');
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
<button type="submit">Sign up</button>
{submitted && <p>Thanks, {submitted}</p>}
</form>
);
}One handler can call several setters. React applies them together in a single re-render, so the screen never shows a half-updated state. The input here is controlled, meaning its value comes from state. A later chapter covers that pattern fully.
Events bubble
Most events bubble. After the handler on the clicked element runs, the same event runs the handlers on each parent, up the tree. A click on a button inside a clickable card triggers both handlers.
import { useState } from 'react';
function Card() {
const [opened, setOpened] = useState(false);
const [saved, setSaved] = useState(false);
return (
<div onClick={() => setOpened(!opened)}>
<p>{opened ? 'Open' : 'Closed'}</p>
<button
onClick={e => {
e.stopPropagation();
setSaved(true);
}}
>
{saved ? 'Saved' : 'Save'}
</button>
</div>
);
}Without e.stopPropagation(), clicking Save would also toggle the card. Use it sparingly. Stopping propagation can hide events from other code that expects to see them, so check first whether the parent handler can simply ignore the event.
Sending updates up from child components
A child cannot set a parent's state directly. The parent passes a handler as a prop, and the child calls it. Name the prop onSomething and the parent's function handleSomething.
import { useState } from 'react';
function AddButton({ onAdd, label }) {
return <button onClick={onAdd}>{label}</button>;
}
function Total() {
const [total, setTotal] = useState(0);
function handleAdd() {
setTotal(total + 5);
}
return (
<>
<p>Total: {total}</p>
<AddButton onAdd={handleAdd} label="Add 5" />
</>
);
}The state stays in Total. AddButton only knows that it should call onAdd when clicked.
Common errors
- Calling the handler in JSX.
onClick={handle()}runs it during render. WriteonClick={handle}oronClick={() => handle(x)}. - Updating state during render. Setters belong in handlers and effects, not in the body of the component.
- Expecting the new value right after the setter. The variable keeps its old value for the rest of that handler. If you need the new value, compute it first and use it in both places.
- Mutating instead of replacing. Calling
person.name = 'Ana'and then a setter with the same object gives React nothing to compare. Create a new object or array. - Forgetting
preventDefaulton forms. The browser reloads the page and your state is lost. - Using a string for the handler.
onclick="..."is HTML. In JSX it isonClick={fn}.
Handlers and async work
A handler can be an async function. State updates after an await still work, and React batches them in modern versions. The handler still closes over the state from the render that created it. If the user clicks again before the await finishes, the old closure keeps the old values. Use functional updates, covered in a later chapter, when the next value depends on the previous one.
Exercise
A component has const [count, setCount] = useState(0); and renders <button onClick={setCount(count + 1)}>Add</button>. What goes wrong, and how do you fix it?
Show answer
setCount(count + 1) runs during render because it is called, not passed. It queues a state update, which triggers another render, which calls it again, and React throws a "Too many re-renders" error. Pass a function instead: onClick={() => setCount(count + 1)}.
Exercise
A card has an onClick that toggles its details. Inside it, a Delete button has its own onClick that removes the card. Clicking Delete also toggles the details first. Why, and what is one fix?
Show answer
The click event bubbles from the button to the card, so both handlers run. One fix is to call e.stopPropagation() in the Delete handler. Another is to check e.target in the card handler and ignore clicks that came from the button.