Sub topic 8
Avoid chains of Effects that trigger each other
This chapter assumes you know useState, props, and the basic shape of useEffect with a dependency array. You should also know that a state update schedules a re-render. The previous chapters covered event handlers and calculating values during render. This one applies both ideas to a specific smell: several Effects that each set state, so that one Effect's update triggers the next.
What an Effect chain looks like
A chain appears when you reach for an Effect whenever one piece of state should change because another one did. Each Effect watches one value and sets another. The next Effect watches that value, and so on.
The example below is a card game. Placing a gold card increases a counter. After four gold cards the round advances. After round 5 the game ends and an alert shows.
import { useState, useEffect } from 'react';
function Game() {
const [card, setCard] = useState(null);
const [goldCardCount, setGoldCardCount] = useState(0);
const [round, setRound] = useState(1);
const [isGameOver, setIsGameOver] = useState(false);
useEffect(() => {
if (card !== null && card.gold) {
setGoldCardCount(c => c + 1);
}
}, [card]);
useEffect(() => {
if (goldCardCount > 3) {
setRound(r => r + 1);
setGoldCardCount(0);
}
}, [goldCardCount]);
useEffect(() => {
if (round > 5) {
setIsGameOver(true);
}
}, [round]);
useEffect(() => {
if (isGameOver) {
alert('Good game!');
}
}, [isGameOver]);
return (
<>
<p>Round {round}, gold cards: {goldCardCount}</p>
<button disabled={isGameOver} onClick={() => setCard({ gold: true })}>
Place gold card
</button>
<button disabled={isGameOver} onClick={() => setCard({ gold: false })}>
Place plain card
</button>
</>
);
}This code runs and mostly behaves. It still has three problems.
Why chains cause trouble
Extra renders
Setting state inside an Effect schedules another render, and that render runs the next Effect. One click in this component causes up to four renders, and each render passes through a state the user was never meant to see. For example, goldCardCount is briefly 4 before the second Effect resets it to 0. Each intermediate render re-runs the component and its children.
The following diagram shows one click that ends a round.
Brittle code
The flow of the game is spread across four separate blocks. To learn what happens after a click, you must follow the chain by hand. A later change, such as adding a second counter that also feeds into round, can add a new link whose effects overlap with the old ones. Because each Effect fires based on a dependency change, not on a cause, the order and number of runs can surprise you.
Features that break the chain
Suppose you add a "Back" button that restores the game to an earlier step. You set round back to a past value. If an Effect watches round and sets other state, it fires again and changes the state you just restored. Effect chains react to values changing, whatever the reason, so they cannot tell a new move from a restore.
The fix: calculate what you can, handle the rest in the event
Two earlier ideas apply here.
- Anything that can be calculated from existing state should be calculated during render.
isGameOveris exactlyround > 5, so it never needed to be state. - Everything else was caused by one user action, placing a card. That logic belongs in the event handler, where you know what happened and can compute every next value at once.
import { useState } from 'react';
function Game() {
const [card, setCard] = useState(null);
const [goldCardCount, setGoldCardCount] = useState(0);
const [round, setRound] = useState(1);
// Calculated during render. No state, no Effect.
const isGameOver = round > 5;
function handlePlaceCard(nextCard) {
if (isGameOver) {
throw Error('Game already ended.');
}
setCard(nextCard);
if (nextCard.gold) {
if (goldCardCount < 3) {
setGoldCardCount(goldCardCount + 1);
} else {
setGoldCardCount(0);
setRound(round + 1);
if (round === 5) {
alert('Good game!');
}
}
}
}
return (
<>
<p>Round {round}, gold cards: {goldCardCount}</p>
<button disabled={isGameOver} onClick={() => handlePlaceCard({ gold: true })}>
Place gold card
</button>
<button disabled={isGameOver} onClick={() => handlePlaceCard({ gold: false })}>
Place plain card
</button>
</>
);
}A click now causes one render. React batches the three set calls in the handler, and the next render sees the final values. The "Back" button problem also goes away. Restoring a past round just sets state. Nothing watches it and fires side effects, because the side effect (the alert) is tied to the move that ends the game.
Why the handler can compute next values
The handler is a closure over the state from the render in which the click happened. In handlePlaceCard, goldCardCount and round hold the values the user saw when they clicked. You can compute the next values directly from them. Two details matter:
- State variables do not change inside the handler after you call
setX. ReadingroundaftersetRound(round + 1)still gives the old value. Compute the next value once into a local variable if you need it twice. - Use the updater form (
setX(c => c + 1)) when you only have a single update that depends on the previous value. When the decision depends on several state values, as here, compute from the snapshot.
Spotting a chain
The table lists signals that an Effect probably should not exist.
| Signal in the code | What it usually means | Replacement |
|---|---|---|
| An Effect whose only job is to call `setX` | `x` is derived from other values | Calculate `x` during render |
| An Effect whose dependency is state that a click just set | The Effect is replaying the click | Move the logic into the handler |
| Two Effects where one's `set` call is the other's dependency | A chain | Compute all next values in one handler |
| An Effect that resets state when a prop changes | State tied to an identity | Use `key` on the component |
| An Effect that calls a parent callback after local state changes | Parent notification | Call the callback in the same handler |
A good test is to ask why the code runs. If the answer is "because the user did this", it belongs in an event handler. If the answer is "because this component is on screen and must stay in sync with something outside React", it belongs in an Effect.
When a chain is legitimate
Not every sequence of Effects is wrong. Sometimes you cannot compute the next value in a handler, because it comes from the network.
Consider three linked dropdowns. The cities available depend on the selected country, and the areas depend on the selected city. Each list is fetched from a server, so each fetch is a synchronization with an external system. Here the Effects are chained, but each one does real external work.
import { useState, useEffect } from 'react';
function useData(url) {
const [data, setData] = useState(null);
useEffect(() => {
if (url === null) {
setData(null);
return;
}
let ignore = false;
fetch(url)
.then(response => response.json())
.then(json => {
if (!ignore) {
setData(json);
}
});
return () => {
ignore = true;
};
}, [url]);
return data;
}
export default function ShippingForm({ country }) {
const [city, setCity] = useState(null);
const [area, setArea] = useState(null);
const cities = useData('/api/cities?country=' + encodeURIComponent(country));
const areas = useData(
city ? '/api/areas?city=' + encodeURIComponent(city) : null
);
function handleCityChange(e) {
setCity(e.target.value);
setArea(null); // Reset the dependent choice in the same event.
}
return (
<>
<select value={city ?? ''} onChange={handleCityChange}>
<option value="">Choose a city</option>
{(cities ?? []).map(c => (
<option key={c.id} value={c.id}>{c.name}</option>
))}
</select>
<select value={area ?? ''} onChange={e => setArea(e.target.value)}>
<option value="">Choose an area</option>
{(areas ?? []).map(a => (
<option key={a.id} value={a.id}>{a.name}</option>
))}
</select>
</>
);
}Notice what is and is not in an Effect. Fetching is inside the useData Effect, because the network is external. Resetting area when the city changes is not in an Effect. It happens in handleCityChange, in the same event that changed city. If country can change, key the form by country in the parent (<ShippingForm country={country} key={country} />) so city and area reset automatically, as the earlier chapter on keys showed.
The rule is that chain links may exist only where each link talks to something outside React. A link that only moves data from one state variable to another is the smell.
Common mistakes when removing a chain
- Moving the logic but keeping the state. If you move the game-over logic into the handler but leave
isGameOveras state set in the handler, you still carry a value that can drift out of sync withround. Delete it and calculate it. - Reading state right after setting it. Writing
setRound(round + 1); if (round > 5) ...tests the old value. Testround === 5as the code above does, or store the next value in a localconst nextRound = round + 1. - Putting the alert or other side effects in render. The alert is caused by a move, so it goes in the handler. Calling it in the component body runs it on every render, including extra renders in development Strict Mode.
- Splitting logic that must happen together across handlers. If two different handlers (for example, "place card" and "skip turn") both advance the round, extract a plain function such as
advanceRound()and call it from both. Do not create an Effect to share the code. - Assuming you can never use an Effect. Syncing with the network, the DOM, timers, and third-party widgets is what Effects are for.
Exercises
Exercise
A component has const [items, setItems] = useState([]) and const [count, setCount] = useState(0), plus an Effect with dependency [items] that calls setCount(items.length). Rewrite it without the Effect and say how many renders you save per update to items.
Show answer
Delete count as state and calculate it during render: const count = items.length;. Each update to items previously caused two renders: one for items, and one for the setCount called from the Effect. Now it causes one.
Exercise
In the card game, the Effect chain ended with useEffect(() => { alert('Good game!'); }, [isGameOver]) guarded by if (isGameOver). Why does the handler version call alert only when round === 5 and a gold card ends the round, and what bug does this avoid if you later add a "Back" button that restores round?
Show answer
The alert is caused by the move that finishes round 5, so it runs in the handler for that move. An Effect watching isGameOver or round would fire whenever those values reached the end state, including when a restore (the Back button) set them. The handler version ties the alert to the user action instead of to a value change, so restoring state never triggers it.
Exercise
A form has a country select and a city select. The list of cities is fetched from the server by country. When the country changes, city must reset to empty. Which parts belong in an Effect, and which do not?
Show answer
Fetching the city list belongs in an Effect (or a data hook that uses one), because it synchronizes with the network, and it needs cleanup that ignores stale responses. Resetting city does not belong in an Effect. Do it in the country change handler, or key the component by country so its state resets automatically.