Sub topic 7
Put user-triggered logic in event handlers
This chapter assumes you know function components, useState, and the basics of useEffect with a dependency array. It also assumes you know that React re-renders a component when state or props change. Earlier chapters showed how to calculate values during render and how to reset state with a key. This chapter covers the next case: work that happens because the user did something.
The question to ask first
When you write an Effect, ask why this code needs to run. There are two possible answers:
- The user did something specific, such as clicking, typing, or submitting. The code belongs in an event handler, a function you pass to a prop like
onClickoronSubmit. - The component was displayed, or a value it depends on changed, and the component must stay in sync with an outside system. The code belongs in an Effect.
Many bugs come from mixing these up. An Effect re-runs because values changed, and that is not the same as a user having done something. An Effect cannot tell which interaction caused a change, or whether a user caused it at all.
A form that posts from an Effect
Here is a registration form that sends data from an Effect. It stores the data to send in a state variable and posts when that variable changes.
import { useState, useEffect } from 'react';
async function post(url, data) {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
return response.json();
}
function Form() {
const [name, setName] = useState('');
const [jsonToSubmit, setJsonToSubmit] = useState(null);
// Avoid: the Effect only reacts to a state change.
useEffect(() => {
if (jsonToSubmit !== null) {
post('/api/register', jsonToSubmit);
}
}, [jsonToSubmit]);
function handleSubmit(e) {
e.preventDefault();
setJsonToSubmit({ name });
}
return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={e => setName(e.target.value)} />
<button type="submit">Register</button>
</form>
);
}This works in simple cases, but it has several problems.
- The
nullcheck exists only to stop the Effect from posting on mount. You added state to work around the Effect. - The click now goes through a detour: handler, state update, render, Effect, request. The cause (a submit) and the effect (a request) are far apart in the code.
- If the user submits the same data twice,
setJsonToSubmit({ name })creates a new object each time, so the Effect runs again. If you later store a primitive instead, the second submit may not run the Effect at all, because React compares dependencies withObject.isand sees no change. - In development, React Strict Mode mounts, unmounts, and remounts every component once to expose bugs in Effects. An Effect that sends a request can send it twice during that check.
The same logic in an event handler
Move the request into the handler. The user's submit is the cause, so the submit handler is where the request goes.
import { useState } from 'react';
async function post(url, data) {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
return response.json();
}
function Form() {
const [name, setName] = useState('');
function handleSubmit(e) {
e.preventDefault();
// Caused by the user's click, so it belongs in the event handler.
post('/api/register', { name });
}
return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={e => setName(e.target.value)} />
<button type="submit">Register</button>
</form>
);
}The extra state, the null check, and the Effect are gone. The handler runs once per submit, and it runs only when the user submits.
Why handlers are the right place
Event handlers differ from Effects in four ways that matter here.
- They run only in response to an interaction. They do not run on mount, and they do not run again because some unrelated value changed.
- They are allowed to have side effects. Rendering must be pure, but a handler can send requests, show alerts, write to storage, or navigate.
- They see the state from the render in which they were created. The handler's closure holds a snapshot of props and state. The values match what the user saw when they clicked.
- They are not reactive. A handler is not re-run when values it reads change. This is what you want for "do this once, when the user acts."
A notification that fires at the wrong time
The submit example fails in a quiet way. The next one fails in a visible way. A product page shows a "Added to cart" notification, and the developer wrote it as an Effect that watches the cart.
import { useEffect } from 'react';
function ProductPage({ product, addToCart }) {
// Avoid: this is event-specific logic inside an Effect.
useEffect(() => {
if (product.isInCart) {
showNotification(`Added ${product.name} to the shopping cart!`);
}
}, [product]);
function handleBuyClick() {
addToCart(product);
}
function handleCheckoutClick() {
addToCart(product);
navigateTo('/checkout');
}
return (
<>
<button onClick={handleBuyClick}>Buy</button>
<button onClick={handleCheckoutClick}>Checkout</button>
</>
);
}If the cart is saved between visits, a user who opens a product that is already in the cart sees the "Added" notification on page load. They added nothing. Navigating between products can show it again. The Effect cannot tell "the user just added this" from "this was already in the cart."
The fix is to say what happened at the place where it happens.
function ProductPage({ product, addToCart }) {
function buyProduct() {
addToCart(product);
showNotification(`Added ${product.name} to the shopping cart!`);
}
function handleBuyClick() {
buyProduct();
}
function handleCheckoutClick() {
buyProduct();
navigateTo('/checkout');
}
return (
<>
<button onClick={handleBuyClick}>Buy</button>
<button onClick={handleCheckoutClick}>Checkout</button>
</>
);
}This version also shows how to share logic. When two handlers need the same code, extract an ordinary function and call it from both. Do not use an Effect as a shared place to put it.
Deciding between a handler and an Effect
The diagram shows the question to ask for each piece of logic.
The table gives the same guidance with examples.
| Situation | Where it goes | Reason |
|---|---|---|
| User clicks Buy and a request is sent | Event handler | A specific interaction caused it. |
| User submits a form and a toast appears | Event handler | The toast describes what the user just did. |
| Full name shown from first and last name | Render | It can be computed from existing state. |
| Page view logged when the page is displayed | Effect | Display caused it, not a click. |
| Chat connection opened while a room is shown | Effect | The component syncs with an outside system. |
Reading state after a set call
A frequent handler mistake is reading state right after calling its setter and expecting the new value. State is a snapshot for the current render, so the variable has not changed yet.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
// Still the old value: count is 0 in this render's closure.
console.log(count); // logs 0 on the first click
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}People sometimes add an Effect to "react to the new value" because of this. Don't. Compute the next value in a local variable and use it in the handler.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
const nextCount = count + 1;
setCount(nextCount);
saveCount(nextCount);
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}saveCount here stands for any outside call, such as writing to localStorage or posting to a server. The handler knows the next value, so no Effect is needed to find out about it.
Calling several setters in one handler is also fine. React batches all updates made inside one event into a single re-render, so you do not pay for several renders.
Edge cases
Logic that is shared between a handler and display
Sometimes the same outside system is touched both when the user acts and when the component appears. Keep them apart. A click that logs "button clicked" belongs in the handler. A "page viewed" log belongs in an Effect, because the page being shown is the cause. Merging them into one Effect loses the information about which one happened.
Several steps that follow one action
If one click should update three pieces of state and then send a request, do all of it in the handler. It is tempting to set the first piece of state and let Effects handle the rest, each triggered by the one before. That pattern is a chain of Effects. It adds extra renders and makes the order hard to follow, and a later chapter covers it in detail. For now, the rule is to do all the steps in the handler, where you can see them together.
Handlers that outlive the render
A handler passed to setTimeout or to an asynchronous callback still sees the snapshot from the render that created it. If you need the newest state after an await, use the functional form of the setter, for example setCount(c => c + 1). This is a handler concern, so it does not need an Effect either.
A quick test with Strict Mode
In development, Strict Mode runs your Effects an extra time on mount. If this extra run causes a visible problem, such as a duplicate purchase or a doubled request, ask whether the code should be in a handler. If it was caused by a click, the bug is a sign that it was in the wrong place. Do not add a useRef flag to suppress the second run. That hides the symptom and keeps the wrong design.
Common errors
- A "trigger" state variable. The handler sets a flag and an Effect acts on it. Remove the flag and do the work in the handler.
- An Effect that checks
if (isFirstRender). This guard is a sign the code was caused by an interaction, not by display. - An Effect that shows a message after a state change. The message should be shown by the code that changed the state.
- Duplicated logic across handlers. Extract a plain function. Do not move it into an Effect.
- Reading state right after setting it. Compute the next value in a local variable instead.
Summary of the working model
React renders the component as a pure calculation. After the render is on screen, it runs Effects to sync with outside systems. Between renders, when the user interacts, it runs your handler, which can have side effects and update state. Each tool has one cause: handlers answer to the user, Effects answer to what is displayed, and render answers to props and state.
Exercise
A component keeps const [shouldSave, setShouldSave] = useState(false). A Save button calls setShouldSave(true). An Effect with [shouldSave] as its dependency calls saveDraft(text) and then setShouldSave(false). Rewrite the component's logic so it needs neither the state variable nor the Effect, and explain why the original design is fragile.
Show answer
Call saveDraft(text) directly in the Save button's click handler: function handleSaveClick() { saveDraft(text); }. Delete shouldSave and the Effect. The original is fragile because the Effect runs after render and depends on a flag that only carries the click. It must reset the flag with a second state update, which causes an extra render. It can also run at the wrong time, such as on mount in Strict Mode, if the flag is ever initialized to true. The click is the cause, so the handler is the right place.
Exercise
A page logs trackEvent('product_viewed', id) when a product page is shown, and trackEvent('add_to_cart', id) when the user clicks Add. Which of the two calls belongs in an Effect, and which belongs in an event handler? Why?
Show answer
product_viewed belongs in an Effect with [id] as the dependency, because the page being displayed causes it and no user action does. add_to_cart belongs in the click handler for the Add button, because a specific click causes it. Putting add_to_cart in an Effect could log it when the page loads with an item already in the cart.