Deleting Effects You Do Not Need
Take a component weighed down by effects, delete the ones that only mirror values or react to events, and keep the one that genuinely synchronises with an external system.
Contentsand lesson path
On this page
- The problem
- Step 1: compute during render instead
- Step 2: keep the effect that synchronises
- Step 3: event logic goes in the handler
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Effects & Data Fetching in React
- Effects as Synchronization, Not Lifecycle Concept · 20 min
- Deleting Effects You Do Not Need Worked example · 20 min
- Refs and Custom Hooks Worked example · 20 min
- Fetching Data Safely Inside Components Worked example · 25 min
- Lab: Server State with a Query Cache Lab · 30 min
- Check: Effect and Fetching Bug Hunt Knowledge check · 8 questions
What you will learn
- Decide when an effect is needed versus computing during render or handling logic in an event handler, and write effects with complete dependencies and cleanup.
Prerequisites: React Components & State, Async JavaScript & Fetch
01. The problem
Effects have a way of multiplying. One developer adds an effect to filter a list; the next adds an effect to count the filtered list; someone else routes a button click through a state flag so an effect can react to it. Each step looks harmless, and the component ends up doing its work in three renders instead of one, with windows in between where the screen disagrees with itself.
The test from the previous lesson cuts through this: an effect is for synchronising with an external system. State, props and displayed values are internal to React, and logic that answers a particular user action belongs in that action's handler. This lesson takes a component with three typical effects, deletes the two that should never have existed, and keeps the one that earns its place — measuring the difference as we go.
import { useEffect, useState } from 'react';
export default function BookShelf({ books, query, onRender }) {
onRender();
const [visible, setVisible] = useState([]);
const [count, setCount] = useState(0);
useEffect(() => {
setVisible(
books.filter((b) => b.title.toLowerCase().includes(query)),
);
}, [books, query]);
useEffect(() => {
setCount(visible.length);
}, [visible]);
return (
<p>
{count} of {books.length} books match "{query}"
</p>
);
}onRender is a test hook that counts renders; ignore it for a moment and read the two effects. Both copy data that React already has into state, and on the first mount React usually lets the browser paint before it runs them — so the first frame shows a count of 0, until the effects run and force re-renders. That is the classic "flicker of stale content" symptom.
02. Step 1: compute during render instead
The first effect filters books by query and stores the result in state. Ask the direct question: is visible something that arrives from outside, or something derived from values React already holds? It is derived — so the effect and the state behind it are both unnecessary. Compute while rendering:
const visible = books.filter((b) => b.title.toLowerCase().includes(query.toLowerCase()));
When books or query change, the component re-renders and the filter runs again, in the same pass that draws the new screen. There is no window in which visible lags behind its inputs, because there is no stored copy to go stale. That lag is the quiet danger of the mirror-in-an-effect pattern: two copies of the same truth that can disagree. Add a book while the fetch of the next page is in flight, and the stored visible no longer matches books until the effect happens to run again — a bug class that simply cannot exist when there is only one source. The same reasoning removes the second effect: visible.length needs no state and no effect either — read it where you display it.
Resist reaching for useMemo here by default. Memoisation pays for itself only when the calculation is genuinely expensive or the value is consumed by something equally expensive; a filter over a few hundred books is neither. Write the plain expression first, and measure before caching.
03. Step 2: keep the effect that synchronises
The refactor is not just deletion. This shelf also remembers the query between visits by writing it to localStorage — and localStorage is an external system. That job survives, now the only effect in the component:
import { useEffect } from 'react';
export default function BookShelf({ books, query, onRender }) {
onRender();
const visible = books.filter((b) =>
b.title.toLowerCase().includes(query.toLowerCase()),
);
useEffect(() => {
localStorage.setItem('bookShelfQuery', query);
}, [query]);
return (
<p>
{visible.length} of {books.length} books match "{query}"
</p>
);
}before: 3 renders, text: "2 of 5 books match "react""
after: 1 render, text: "2 of 5 books match "react""
localStorage["bookShelfQuery"] = "react"Same sentence on screen, a third of the renders, and no intermediate frame where the count is wrong. The render counts came from rendering both versions in Chromium against the same five books (the titles of the mock API in the fetching lesson) with the query "react" — the before version renders, runs its effects, and re-renders twice more to catch up with itself. The counts assume Strict Mode is off; under Strict Mode every render happens twice in development, but the ratio between the two versions is the point.
The localStorage effect would behave the same way if it were dropped: the query simply would not be remembered. It stays because the browser's storage is outside React's model, exactly like the tab title in the previous lesson.
04. Step 3: event logic goes in the handler
The third common pattern is subtler: code that should answer one user action gets routed through a state flag, so an effect can watch for the flag changing. Every click that toggles the flag is an "event" the effect then reacts to — indirect, hard to trace, and prone to firing on the wrong render or firing twice. The direct version needs no effect at all:
import { useState } from 'react';
export default function SaveButton({ onSave }) {
const [saved, setSaved] = useState(false);
return (
<>
<button
type="button"
onClick={() => {
onSave();
setSaved(true);
}}
>
Save note
</button>
<p role="status">{saved ? 'Note saved.' : 'Not saved yet.'}</p>
</>
);
}click "Save note" once -> status "Note saved.", onSave called 1 timeThe click caused the save, so the click handler does the saving and updates whatever state the confirmation needs. A useful filter: if you can point at the interaction that should cause the work, put the work in that interaction's handler. Reach for an effect when the work must happen because the component is on screen with certain values — regardless of what the user just did.
05. Common mistakes
06. Check your understanding
07. Apply it
Audit one component from the book-search practice project (or any project of yours):
- List every effect and classify it: external synchronisation, event logic in disguise, or derived value.
- Delete the derived-value effects and compute during render; move disguised event logic into its handler.
- Add a render counter like the one in this lesson and compare before and after.
- Confirm the visible output is unchanged — deleting effects should never change what the user sees, only when and how often the work happens.
08. Review prompt
Without looking back: what two questions identify a deletable effect? Why does mirroring state into more state cause a stale frame, and why does computing during render not? When is useMemo worth it? And what distinguishes the one effect in this lesson that stayed?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.