Sub topic 1
Event Handlers Respond to Interactions, Effects Synchronize
React gives you two places to put code that does something beyond rendering: event handlers and Effects. Choosing the right one is the base for everything else in this tutorial. useEffectEvent exists because some logic falls between the two.
Prerequisites
This chapter assumes you already know:
- JavaScript functions, closures, and arrow functions
- React function components, props, and state with
useState - Basic use of
useEffect, including cleanup functions - The dependency array of
useEffect
Two Kinds of Side Effects
Rendering should be pure. It turns props and state into JSX and does nothing else. Anything that touches the outside world, such as a network call, a subscription, or a log entry, has to go somewhere else.
- Event handlers run because the user did something specific: clicked, typed, or submitted. They run once per interaction.
- Effects run because the component is on screen and has to stay in sync with an external system. They run after rendering, and again whenever the values they depend on change.
The question to ask about any piece of code is: why does this run? If the answer is "the user pressed Send," the code belongs in an event handler. If the answer is "the component is showing room X, so we must be connected to room X," it belongs in an Effect.
A Chat Room Example
A chat room needs both kinds of logic. Sending a message happens because of a click. Staying connected happens because the room is visible.
// 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}`);
}// ChatRoom.jsx
import { useState, useEffect } from 'react';
import { createConnection, sendMessage } from './chat.js';
export default function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
// Effect: keep the connection in sync with roomId
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
// Event handler: runs only when the user clicks Send
function handleSendClick() {
sendMessage(message);
setMessage('');
}
return (
<>
<h1>Welcome to {roomId}</h1>
<input value={message} onChange={(e) => setMessage(e.target.value)} />
<button onClick={handleSendClick}>Send</button>
</>
);
}Typing in the input changes message and re-renders the component, but nothing is sent. sendMessage runs only when the button is clicked. Switching roomId from "general" to "travel" makes the Effect disconnect from the old room and connect to the new one, and no click is needed for that.
Comparing the Two
| Row | Event handler | Effect |
|---|---|---|
| Triggered by | A specific user interaction | Rendering, plus changes to dependencies |
| Runs | Once per interaction | After commit, again when dependencies change |
| Purpose | Respond to what the user did | Keep an external system in sync |
| Reads values | From the render where the event fired | From the render that ran the Effect |
Common Mistakes
The most common mistake is putting interaction logic in an Effect. For example, you might set a submitted flag in state and then send the request from an Effect that watches the flag. That adds an extra render, and it can resend the request when unrelated state changes. If the code exists because of a click, call it from the click handler.
The opposite mistake is connecting only in a click handler. Then the connection isn't updated when roomId changes for some other reason, such as navigation.
Some logic doesn't fit cleanly. Suppose you want to show a "Connected!" notification in the current theme. Connecting is synchronization, but the notification only reads the theme and shouldn't trigger reconnects. The rest of this tutorial covers that middle case.
Exercise
A product page must log an analytics "page view" whenever its productId prop changes, and must add the product to the cart when the user clicks "Buy". Which logic belongs in an Effect and which in an event handler?
Show answer
The page-view log belongs in an Effect with productId as a dependency, because it runs to stay in sync with which product is displayed. Adding to the cart belongs in the click event handler, because it happens only because the user pressed "Buy".
Exercise
A developer sends a form's data from an Effect that runs when a submitted state variable becomes true. What is wrong with this, and what should they do instead?
Show answer
Submitting is caused by a specific interaction, so it belongs in the submit event handler. Routing it through state and an Effect adds an extra render and can resend the request if the Effect re-runs. They should call the send function directly in the submit handler.