Sub topic 8
Effect or event handler?
This chapter assumes you know useState, how a component re-renders, and the basics of useEffect and its dependency array. It covers how to decide where a piece of side-effect code belongs.
The deciding question
Ask this: why does this code need to run?
- If it runs because the user did something, such as a click, a submit, or a key press, put it in an event handler.
- If it runs because the component is shown on screen, or because a value it depends on changed, put it in an effect.
An event handler answers "what happens when the user does X". An effect answers "what must stay in sync with the outside world while this component is on screen".
A worked example
Consider a message form. Sending the message is a reaction to a click. Connecting to the chat room is not tied to any click. The connection must exist whenever the component shows a given room.
import { useEffect, useState } from 'react';
function createConnection(roomId) {
return {
connect() { console.log(`Connected to ${roomId}`); },
disconnect() { console.log(`Disconnected from ${roomId}`); },
};
}
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
// Effect: keeps a connection in sync with roomId.
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
// Event handler: runs only when the user submits.
function handleSubmit(e) {
e.preventDefault();
fetch('/api/messages', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ roomId, message }),
});
setMessage('');
}
return (
<form onSubmit={handleSubmit}>
<input value={message} onChange={(e) => setMessage(e.target.value)} />
<button type="submit">Send</button>
</form>
);
}The POST request is not in an effect. If it were, the message would be sent whenever roomId or message changed, not when the user pressed Send.
Why the distinction matters
Effects re-run when their dependencies change. Event handlers run once per event. Putting user-triggered work in an effect causes three common problems:
- The code runs at the wrong time, for example when a dependency changes for an unrelated reason.
- You need flags or state such as
shouldSubmitto tell the effect when to act. - Strict Mode runs the effect twice in development, which can send a duplicate request.
A handler also has direct access to the event and to the values from the render in which the user acted. An effect only sees its dependencies.
Common mistakes
| Pattern | Problem | Fix |
|---|---|---|
| Set `submitted` to true in a handler, then POST in an effect | Extra render and indirect control flow | POST directly in the handler |
| Show a notification in an effect that watches state | Fires on every change of that state, not only after a user action | Show it in the handler that caused the change |
| Fetch in a click handler for data the screen always needs | Data is missing until a click, and it does not refresh when the ID changes | Fetch in an effect that depends on the ID |
Some code truly needs both. Analytics that log a page view belong in an effect, because the visit is caused by display. Analytics that log a button click belong in the handler.
Exercise
A component sends an analytics event "purchase completed" after the user clicks Buy and the request succeeds. A teammate puts this call in a useEffect that depends on an order state value. Where should it go, and why?
Show answer
Put it in the Buy click handler, after the request succeeds. The event is caused by a user action, not by the component being displayed. An effect tied to order would also fire whenever order changes for other reasons, and Strict Mode would run it twice in development.