Part 06 / Topic 5 of 7
Effects for derived state - this course's most emphasized effect mistake
A value that can be computed from props/state you already have should be computed during render - never copied into its own useState and "kept in sync" with an effect. examples/04_derived_state_antipattern.jsx filters a fixed list of trains by a search term two ways:
// examples/04_derived_state_antipattern.jsx
export function TrainSearchViaEffect({ searchTerm }) {
const [filteredTrains, setFilteredTrains] = useState(TRAINS);
useEffect(() => {
setFilteredTrains(TRAINS.filter((train) => train.toLowerCase().includes(searchTerm.toLowerCase())));
}, [searchTerm]);
// ...
}
export function TrainSearchDuringRender({ searchTerm }) {
const filteredTrains = TRAINS.filter((train) => train.toLowerCase().includes(searchTerm.toLowerCase()));
// ...
}
Both end up showing the right trains - this is not a correctness bug. The cost is a wasted render: TrainSearchViaEffect renders once with the old (or initial) list, then its effect fires and calls setFilteredTrains, forcing a second render just to show what the first render could already have computed. A render counter (a useRef incremented in the component body, shown in each example) really proves it (examples/04_derived_state_antipattern.test.jsx): mounting TrainSearchViaEffect and changing searchTerm once afterward costs 4 renders total; TrainSearchDuringRender, doing the identical filter as a plain variable with no effect, costs 2 - exactly half, for the exact same visible result.
๐ Going deeper: this is a different problem from slow renders, which is Part 12's job, deliberately much later in this course (see
DESIGN-NOTES.md- Part 12 opens by profiling a genuinely slow list before introducinguseMemo/useCallback/React.memoat all). This section's fix needs zero memoization APIs - it needs removing auseState/useEffectpair that should never have existed.
Done here? The practice set for Part 6 โ including the solutions โ is on the part page.