Sub topic 8
Effect or event handler?
This chapter assumes you can write function components with useState, and that you know the useEffect basics from earlier chapters: the dependency array, cleanup, and the fact that effects run after render. Here you learn how to decide where a piece of logic belongs.
The deciding question
Ask one question about the code: why does it need to run?
- If it runs because the user did something specific (clicked, typed, submitted), put it in an event handler.
- If it runs because the component is on screen and must stay in sync with something outside React, put it in an effect.
An event handler answers "what should happen when this occurs?" An effect answers "what should this component stay connected to while it is displayed?"
Handlers and effects differ in how they run:
| Row | Event handler | Effect |
|---|---|---|
| Triggered by | A specific interaction | Rendering (setup after commit, re-run when dependencies change) |
| Knows what the user did | Yes, it receives the event | No, it only sees values from the render |
| Can be re-run by React | No | Yes (dependency changes, Strict Mode in development) |
| Needs cleanup | No | Often |
| Typical use | Submit a form, send a message, start a purchase | Connect to a server, subscribe, sync the title, log a page view |
A worked example: submitting a form
Many people move a user action into an effect by first storing the action in state. The effect then "reacts" to that state.
import { useEffect, useState } from 'react';
// Avoid: the submit is modeled as state, then an effect reacts to it
function NewsletterFormWithEffect() {
const [email, setEmail] = useState('');
const [submittedEmail, setSubmittedEmail] = useState(null);
useEffect(() => {
if (submittedEmail === null) return;
fetch('/api/subscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: submittedEmail }),
});
}, [submittedEmail]);
function handleSubmit(e) {
e.preventDefault();
setSubmittedEmail(email);
}
return (
<form onSubmit={handleSubmit}>
<input value={email} onChange={(e) => setEmail(e.target.value)} />
<button type="submit">Subscribe</button>
</form>
);
}This code has three problems:
- The second submit does nothing. If the user submits the same address twice,
setSubmittedEmailreceives an identical string. The state does not change, the dependency does not change, and the effect does not run. - The request depends on rendering. If a parent later
submittedEmailalready set, or Strict Mode re-runs the effect in development, the POST can fire again with no user action. - The cause is hidden. To learn why a request was sent, a reader must trace a state variable, not read the submit handler.
The fix is to do the work where the event happens:
import { useState } from 'react';
function NewsletterForm() {
const [email, setEmail] = useState('');
const [status, setStatus] = useState('idle');
async function handleSubmit(e) {
e.preventDefault();
setStatus('sending');
try {
const res = await fetch('/api/subscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
setStatus('done');
} catch (err) {
setStatus('error');
}
}
return (
<form onSubmit={handleSubmit}>
<input value={email} onChange={(e) => setEmail(e.target.value)} />
<button type="submit" disabled={status === 'sending'}>
Subscribe
</button>
{status === 'done' && <p>Subscribed.</p>}
{status === 'error' && <p>Something went wrong.</p>}
</form>
);
}Each submit sends exactly one request. The handler has the event, the current email, and the freedom to be async without any cleanup logic.
Same component, two kinds of logic
A single component often needs both. Consider a product page:
import { useEffect } from 'react';
function showNotification(message) {
console.log(message);
}
function logAnalytics(name, data) {
console.log(name, data);
}
function ProductPage({ product, addToCart }) {
// Effect: the page is displayed, so record that it was viewed.
useEffect(() => {
logAnalytics('page_view', { productId: product.id });
}, [product.id]);
// Event handler: the user clicked, so add to cart and notify.
function handleBuyClick() {
addToCart(product);
showNotification(`Added ${product.name} to the cart!`);
}
return (
<div>
<h1>{product.name}</h1>
<button onClick={handleBuyClick}>Buy</button>
</div>
);
}The page view is a consequence of the component being shown, so it belongs in an effect. Notifying the user is a consequence of a click, so it belongs in the handler.
Now consider a tempting mistake. Suppose the parent passes product.isInCart, and you write this to show the notification:
useEffect(() => {
if (product.isInCart) {
showNotification(`Added ${product.name} to the cart!`);
}
}, [product]);This shows a notification every time the page opens for a product that is already in the cart. The same happens after a reload, when the cart was restored from storage. The state says "the product is in the cart", which is a fact about the world. It does not say "the user just clicked Buy". Only the handler knows the second thing.
Chains of effects
A related pattern is an effect that sets state, which triggers a second effect, which sets more state. For example, a "Buy" flow might use setCart, then an effect that sets setCheckoutReady, then an effect that sets setPaymentOpen.
Chains like this cause several problems:
- Each link adds a render pass, so the UI flickers through intermediate states.
- The order of events is spread across several hooks and is hard to follow.
- Any link can fire for reasons you did not intend, such as a parent re-render or a restored state.
When all the updates come from one user action, compute the next values and set them together in the handler. React batches those state updates into one render.
There is one legitimate chain. Some state depends on the result of a previous network request, such as a dropdown of cities that depends on the selected country, and fetching each list is a real synchronization with a server. Even then, each effect should connect to something outside React. It should not just pass values between state variables.
Choosing: a decision flow
Edge cases
One handler, many effects. Several unrelated pieces of synchronization belong in separate effects. Each effect should describe one connection, so each one has its own dependencies and cleanup.
Shared logic. If a handler and an effect need the same code, extract a plain function and call it from both. Do not route one through the other by setting state.
function sendMessage(roomId, text) {
return fetch(`/api/rooms/${roomId}/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
});
}Connections versus messages. A chat component connects to a room in an effect, because the connection should exist while the room is displayed and change when roomId changes. Sending a message is a handler, because it happens when the user presses Send. Mixing them up produces a bug where changing rooms resends the last message.
Events that originate outside React. A window resize or a WebSocket message is an event too, but React does not manage it. You subscribe in an effect, because subscribing is the synchronization. The code you run when the event arrives is a handler that you registered.
Summary of the rules
- Run code from a handler when a specific interaction causes it.
- Run code from an effect when displaying the component requires it to stay synchronized with an external system.
- Do not use state as a message from a handler to an effect.
- Do not use an effect to pass values between state variables.
Exercise
A component has const [saveRequested, setSaveRequested] = useState(false). The Save button calls setSaveRequested(true). An effect with [saveRequested] as its dependency sends a PUT request when it is true, then calls setSaveRequested(false). Name two things that can go wrong and describe the fix.
Show answer
First, the effect can send the request without a click, for example when the state is restored to true, or twice when Strict Mode re-runs the effect in development. The second set to false also causes an extra render. Second, the cause of the request is hidden in a state flag, so a reader cannot see from the button what it does. The fix is to remove saveRequested and send the PUT request directly in the Save button's click handler, tracking a status such as 'saving' for the UI if needed.
Exercise
For each task, say whether it belongs in an event handler or an effect: (a) open a WebSocket to the room whose id is in props, (b) send a chat message when the user presses Enter, (c) set document.title to the current unread count, (d) show a "Saved" toast after the user clicks Save.
Show answer
(a) Effect, because the connection must exist while the room is displayed and change with roomId. (b) Event handler, because a specific key press causes it. (c) Effect, because it keeps an outside system (the document) in sync with the rendered state. (d) Event handler, because the click causes the toast. An effect watching a "saved" flag would also show the toast on unrelated re-renders or restored state.