Sub topic 1
Event Handlers Respond to Interactions, Effects Synchronize
React gives you two places to put logic that does more than compute JSX: event handlers and Effects. They look similar because both run code with side effects, such as sending a request, writing to storage, or opening a connection. They are triggered by different things, though, and that difference explains everything else in this tutorial. useEffectEvent exists because some code sits awkwardly between the two. Before you can see that gap, you need a clear picture of what each one is for.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript functions, closures, and arrow functions
- React function components, props, and state with
useState - Basic use of
useEffect, including returning a cleanup function - What the dependency array of
useEffectdoes at a basic level
Later chapters cover reactive values and dependencies in detail. Here, the goal is the mental model: why a piece of code belongs in a handler or in an Effect.
Two Kinds of Side-Effect Code
A component's body should be pure. Given the same props and state, it returns the same JSX and changes nothing outside itself. Real apps still need to change things outside themselves, so React offers two places for that work.
| Row | Event handler | Effect |
|---|---|---|
| Triggered by | A specific user interaction (click, submit, key press) | Rendering: the component appeared on screen, or values it uses changed |
| Question it answers | "What should happen because the user did this?" | "What external system should be kept in sync with what's on screen?" |
| Runs | Once per interaction | After commit, then again whenever its dependencies change |
| Has cleanup | No | Yes, optionally, before re-running and on unmount |
| Typical work | Submit a form, send a message, add to cart | Connect to a server, subscribe to events, sync a widget |
The useful test is the cause. Ask what caused the code to need to run. If the answer is "the user pressed this button," the code goes in an event handler. If the answer is "the component is showing this room, so it must be connected to this room," the code goes in an Effect.
A Worked Example: A Chat Room
Consider a chat room component with two requirements:
- While the component is visible, it stays connected to the selected room.
- When the user clicks Send, the current message is sent.
Here is a minimal fake chat module so the example runs on its own:
// chat.js
export function createConnection(roomId) {
return {
connect() {
console.log(`Connecting to "${roomId}"...`);
},
disconnect() {
console.log(`Disconnected from "${roomId}"`);
},
};
}
export function sendMessage(message) {
console.log(`Sending: ${message}`);
}And the component:
// App.js
import { useState, useEffect } from 'react';
import { createConnection, sendMessage } from './chat.js';
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
// Effect: keep the connection in sync with the selected room
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
// Event handler: respond to one specific interaction
function handleSendClick() {
sendMessage(message);
setMessage('');
}
return (
<>
<h2>Welcome to the {roomId} room</h2>
<input value={message} onChange={(e) => setMessage(e.target.value)} />
<button onClick={handleSendClick}>Send</button>
</>
);
}
export default function App() {
const [roomId, setRoomId] = useState('general');
return (
<>
<label>
Choose the chat room:{' '}
<select value={room) => setRoomId(e.target.value)}>
<option value="general">general</option>
<option value="travel">travel</option>
<option value="music">music</option>
</select>
</label>
<hr />
<ChatRoom roomId={roomId} />
</>
);
}Why sending a message is an event handler
The user w the moment they click. Typing into the input changes message and re-renders the component, but nobody wants a message sent on every keystroke. Sending is tied to the click and to nothing else, so it lives in handleSendClick.
Event handlers are not reactive. They read message at the moment they run, and a change to message alone never runs them.
Why connecting is an Effect
No interaction says "connect now." The user might reach this screen by navigating, by a page load, or by picking a room from the dropdown. In every case the requirement is the same: whenever ChatRoom is on screen showing room X, it is connected to room X.
That is synchronization. The Effect describes how to start syncing (connect) and how to stop (disconnect). React decides when to run those based on what is rendered. When roomId changes from general to travel, React runs the cleanup for general and then the setup for travel. When the component unmounts, React runs the final cleanup.
Thinking in Synchronization, Not Lifecycles
A common mistake is to read an Effect as "run this on mount" plus "run this on unmount." That framing breaks as soon as props change. The connection Effect is not a mount hook. It describes one process: being connected to roomId. React may start and stop that process many times over the component's life, once per room the user visits.
Seen this way, the dependency array is a description rather than a scheduling trick. [roomId] says "this synchronization depends on roomId." If roomId is the same as last render, the existing connection is still correct and React skips the Effect.
Common Errors
Putting interaction logic in an Effect
Here is a tempting but wrong approach to "send when the user clicks":
import { useState, useEffect } from 'react';
import { sendMessage } from './chat.js';
function BadSend() {
const [message, setMessage] = useState('');
const [sent, setSent] = useState(false);
// Wrong: an Effect responding to an interaction via a flag
useEffect(() => {
if (sent) {
sendMessage(message);
setSent(false);
}
}, [sent, message]);
return (
<>
<input value={message} onChange={(e) => setMessage(e.target.value)} />
<button onClick={() => setSent(true)}>Send</button>
</>
);
}
export default BadSend;This code works, but it routes an interaction through state and an extra render. It is harder to follow, and the Effect re-runs whenever message changes. The cause of the send is the click, so the send belongs in the click handler.
Putting synchronization logic in an event handler
The reverse mistake is connecting inside the dropdown's onChange. That covers the case where the user picks a room. It misses the first render, navigation from elsewhere, and any other path that changes roomId. It also leaves disconnecting on unmount to you. Synchronization driven by what is rendered belongs in an Effect.
Forgetting cleanup
An Effect that connects without disconnecting leaks a connection every time roomId changes. Every setup that acquires something (connection, subscription, interval, listener) needs a matching cleanup.
The Gap This Tutorial Addresses
So far the split is clean: interactions go to handlers, synchronization goes to Effects. Real requirements are messier. Suppose that when the connection succeeds, you want to show a "Connected!" notification styled with the current theme. The notification happens inside the Effect, because it responds to the connection. It is not part of the synchronization, though. Changing the theme should not reconnect to the chat server.
That code has the timing of an Effect and the intent of an event handler. It should run because of something the Effect did, but it should not make the Effect re-run when the values it reads change. The next chapters build the vocabulary for that distinction, starting with reactive values and how dependencies drive re-synchronization. Then they introduce useEffectEvent as the tool for it.
Exercises
Exercise
A product page must log an analytics "page view" whenever the user lands on a product, including on first load and when navigating between products. Should this go in an event handler or an Effect, and why?
Show answer
An Effect. The log is caused by the product being displayed, not by any specific interaction. A user can reach the page in many ways (direct link, navigation, back button), and the Effect runs whenever the displayed product changes, so it covers all of them.
Exercise
A form has a "Buy" button that sends a POST request to purchase the item. A teammate puts the request in a useEffect that runs when a purchased state flag becomes true. What is wrong, and how would you fix it?
Show answer
The purchase is caused by the click, so it belongs in the button's event handler. Routing it through state and an Effect adds an extra render and makes the logic harder to follow. It can also fire again if the Effect re-runs, for example in Strict Mode or when another dependency changes. Call the POST request directly in the onClick handler.
Exercise
In the ChatRoom example, the user types "hello" into the message input. How many times does the connection Effect run, and how many times does handleSendClick run?
Show answer
Neither runs. Each keystroke updates message and re-renders, but the Effect depends only on roomId, which did not change, and handleSendClick runs only when the Send button is clicked.
Exercise
You want to show a toast with the current theme when the chat connection succeeds, without reconnecting when the theme changes. Why doesn't this fit cleanly into either an event handler or a plain Effect?
Show answer
No user interaction triggers it, since the connection succeeding triggers it, so an event handler can't own it. If it lives in the Effect and reads theme, theme becomes a dependency, and changing the theme would reconnect. The code needs Effect timing without being reactive to theme, which is the gap useEffectEvent fills.