Effects are for keeping something outside React in step: a timer, a
connection, the network. They're often used for other things too, and each one
costs an extra render and makes the code harder to follow. This board has three
such effects. It logs render every time App renders:
console.log("render");
// 1. Keep the visible cards in step with the query.
useEffect(() => {
setVisible(cards.filter((card) => card.title.toLowerCase().includes(query.toLowerCase())));
}, [cards, query]);
// 2. Clear the selection whenever the query changes.
useEffect(() => {
setSelectedId(null);
}, [query]);
// 3. Say something when a card is added.
useEffect(() => {
if (cards.length > starterCards.length) setMessage(`Added "${cards.at(-1).title}"`);
}, [cards]);npm install and npm run dev. Count the renders
Clear the console, type one letter in the search box, and count the render lines. Then do the same for Add a card.
What you'll see
Two renders for each. The first render shows the old visible cards, and only then does effect 1 copy the new list into state, which causes the second render. The page briefly shows stale data on every keystroke.
1. Values you can compute: compute them
Effect 1 copies a filtered list into visible. That's Day 1's derived value
again. Delete the effect and the visible state, and compute it:
const visible = cards.filter((card) => card.title.toLowerCase().includes(query.toLowerCase()));2. Resetting because of an event: do it in the handler
Effect 2 clears the selection "whenever the query changes". But the query only changes because the user typed. Do both at once, in the handler:
onChange={(e) => {
setQuery(e.target.value);
setSelectedId(null);
}}React batches the two updates into one render. (When a whole component should
start fresh because a prop changed, use a key, as on Day 1.)
3. Responding to a user action: do it in the handler
Effect 3 says "a card was added" by watching cards grow. It works by
accident: it also fires if anything else ever makes cards longer, such as
loading saved cards. The message is about the click, so put it in the click
handler:
function addCard() {
const card = { id: Date.now(), title: "New card", column: "todo", minutes: 15 };
setCards([...cards, card]);
setMessage(`Added "${card.title}"`);
}Make all three changes. Now one keystroke, and one added card, each log one render, and there are no effects left.
The question to ask
Before writing an effect, ask why this code should run:
- Because the component is on screen, and something outside React must match it (a subscription, a timer, a request): use an effect.
- Because the user did something: put it in that event's handler.
- Because some state or props changed, and you want another value: compute it during render.
Which tool?
For each, say whether it belongs in an effect, an event handler, or the render.
- Showing 3 cards match under the search box.
- Sending an analytics event when someone presses Buy.
- Connecting to a chat room while a chat panel is open.
- Clearing a form after it's submitted.
- Setting the browser tab's title to the current card's name.
Hint 1: the idea
Identify what causes the work: a user event, external synchronization, or a calculation for the current screen.
Hint 2: a first step
Ask: does it react to the user doing something, to the component being shown, or is it just a value worked out from what's there?
Show one solution
- Render: it's computed from the matching cards.
- Event handler: it's caused by the click.
- Effect: an outside system kept in step while the panel is on screen, with a cleanup that disconnects.
- Event handler: the submit handler, after saving.
- Effect:
document.titleis outside React, and should follow whatever card is shown, however it got there.
Completion is saved in this browser only. It does not measure mastery.