Sub topic 7
Put user-triggered logic in event handlers
This chapter assumes you know function components, useState, props, and the basics of useEffect with a dependency array. You should also know that React re-renders a component when its state or props change.
The question to ask
When you write an Effect, ask why the code needs to run. There are two possible answers.
- The code runs because the component was displayed. Examples are connecting to a chat server or fetching data. This is a job for an Effect.
- The code runs because the user did something. Examples are clicking a button, submitting a form, or typing in a field. This is a job for an event handler.
An event handler is a function you pass to a prop such as onClick or onSubmit. React calls it when that specific interaction happens. The handler knows exactly what happened and can read the current props and state.
The common mistake
A frequent pattern is to store the result of an action in state and let an Effect react to it. Here is a form that registers a user.
import { useState, useEffect } from 'react';
function Form() {
const [name, setName] = useState('');
const [submitted, setSubmitted] = useState(false);
// Avoid this: the Effect reacts to a flag that a click set.
useEffect(() => {
if (submitted) {
post('/api/register', { name });
}
}, [submitted, name]);
return (
<form onSubmit={e => { e.preventDefault(); setSubmitted(true); }}>
<input value={name} onChange={e => setName(e.target.value)} />
<button type="submit">Register</button>
</form>
);
}This code has several problems.
- It adds a
submittedstate variable that exists only to trigger the Effect. - The request depends on
name, so it can fire again if the user edits the field after submitting. - The flow is hard to follow. A click sets state, React re-renders, and then the Effect runs. You cannot read the cause and effect in one place.
The fix
Move the request into the handler that the user's click triggers.
import { useState } from 'react';
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 submitted state and the Effect are gone. The request runs once per submit, with the name the user had at that moment.
Why this matters beyond style
An Effect cannot tell why it ran. It sees only that a dependency changed. In development, React Strict Mode also runs each Effect twice on mount to expose missing cleanup. If a request sits in an Effect that runs on display, you can send it twice. An event handler runs only for the interaction it is attached to.
Compare two real cases.
| Situation | Where the code goes | Reason |
|---|---|---|
| Show a notification after the user buys a product | Event handler | The purchase was caused by a click |
| Send an analytics event when a page is shown | Effect | It happens because the component was displayed |
| Save a form on submit | Event handler | The submit is a user action |
| Connect to a chat room while a screen is open | Effect | The connection must match what is on screen |
Shared logic between handlers
Two buttons may need the same behavior, such as "Buy" and "Checkout". Do not put the shared work in an Effect to avoid repeating yourself. Extract a plain function and call it from both handlers.
function ProductPage({ product, addToCart }) {
function buyProduct() {
addToCart(product);
showNotification('Added ' + product.name);
}
function handleBuyClick() {
buyProduct();
}
function handleCheckoutClick() {
buyProduct();
navigateTo('/checkout');
}
return (
<>
<button onClick={handleBuyClick}>Buy</button>
<button onClick={handleCheckoutClick}>Checkout</button>
</>
);
}Here showNotification and navigateTo stand for functions your app provides. The pattern is what matters: shared code lives in a function, and each handler decides when to call it.
Common errors
- Setting a flag in a handler so an Effect can do the real work. Do the work in the handler.
- Listing a handler's values in an Effect dependency array, which makes the Effect re-run when those values change, not when the user acts.
- Using an Effect to show a message after state changes, when the message belongs to the action that changed the state.
Exercise
A component sets liked to true in an onClick handler. An Effect with [liked] as its dependency then calls sendLike(postId). Rewrite this so no Effect is needed, and explain one bug the original version can have.
Show answer
Call sendLike(postId) inside the click handler, next to setLiked(true), and delete the Effect. The original can send the request when the component mounts with liked already true, or send it again if postId is added to the dependencies and changes. The Effect reacts to state, not to the click, so it cannot tell whether the user acted.