Sub topic 8
Avoid chains of Effects that trigger each other
This chapter assumes you know function components, useState, props, and the basics of useEffect and its dependency array. You should also know that a state update causes a re-render.
The problem: Effects that set state for other Effects
A chain of Effects is a group of Effects where each one sets state, and that state change triggers the next Effect. It often starts with good intentions. One Effect watches a value, calculates something, and stores the result in state. Another Effect watches that state and does more work.
The pattern has two costs:
- Extra renders. Every
setcall in an Effect schedules another render. A chain of three Effects can cause three or four renders for one user action. - Fragile code. The flow of logic is spread across several Effects. To understand what happens when a user clicks a button, you have to trace state changes from one Effect to the next.
A chain can also break when requirements change. Suppose you later need to step back to an earlier value. The Effects will fire again and replay the whole chain.
A worked example
Here is a card game component. When the player gets a card, the Effects update the gold count, the round, and the game state.
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]);
function handlePlaceCard(nextCard) {
if (isGameOver) {
throw Error('Game already ended.');
}
setCard(nextCard);
}
return <button onClick={() => handlePlaceCard({ gold: true })}>Place card</button>;
}Placing one card can trigger this sequence:
There is a second bug. handlePlaceCard checks isGameOver, but that value only changes after several renders. The check can use stale information.
Calculate what you can, update the rest in the handler
Split the state into two groups:
- Values you can calculate.
isGameOverfollows directly fromround, so it does not need its own state. - Values that change because of the user's action.
goldCardCountandroundchange because the player placed a card. Update them in the event handler.
import { useState } from 'react';
function Game() {
const [goldCardCount, setGoldCardCount] = useState(0);
const [round, setRound] = useState(1);
// Calculated during render. No state and no Effect.
const isGameOver = round > 5;
function handlePlaceCard(nextCard) {
if (isGameOver) {
throw Error('Game already ended.');
}
// Calculate every next value in one place.
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 onClick={() => handlePlaceCard({ gold: true })}>Place card</button>
</>
);
}React batches the state updates in the handler into one render. The isGameOver check in the handler now reads a value that is always consistent with the current render.
When a chain is legitimate
Sometimes you cannot calculate the next value in one place. A common case is a series of dropdowns where each selection loads options from the network, and those options depend on the previous selection. Each fetch is a real synchronization with an external system, so each one is a valid Effect.
Even then, check whether the Effects only copy state from one place to another. If an Effect exists to turn one piece of state into another piece of state, you can usually remove it.
A checklist
When you see an Effect that sets state, ask these questions in order:
- Can the value be calculated from props and state during render? If so, calculate it.
- Did the change happen because of a user action? If so, put the logic in the event handler.
- Is the Effect talking to something outside React, such as the network? If so, keep it and write cleanup.
Exercise
A component has one Effect that watches items and calls setTotal(items.reduce(...)), and a second Effect that watches total and calls setIsFreeShipping(total > 50). How would you remove both Effects?
Show answer
Calculate both values during render: const total = items.reduce(...); and const isFreeShipping = total > 50;. Neither value is a separate piece of state, because both follow from items. If the sum is expensive, wrap it in useMemo.
Exercise
Why is the check if (isGameOver) in the first version of handlePlaceCard unreliable?
Show answer
isGameOver is set by the last Effect in the chain, after several renders. When the handler runs, it reads the value from the current render, which may not yet reflect the result of earlier Effects. Calculating isGameOver during render removes the delay.