Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 20 min · revision 3

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

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.

JSX · book-shelf-before.jsx
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 &quot;{query}&quot;
    </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:

JSX · book-shelf-after.jsx
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 &quot;{query}&quot;
    </p>
  );
}
Expected output (both versions rendered with the same data)
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:

JSX · save-button.jsx
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>
    </>
  );
}
Expected output (clicking Save note once)
click "Save note" once -> status "Note saved.", onSave called 1 time

The 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

Practice check · 3 questions

Delete or keep?

Judge each effect: does it earn its place?

Q1. A component filters about 200 books with a plain expression during render. A teammate asks to wrap it in `useMemo` "for performance". What does this lesson recommend?
Q2. A `Toggle` keeps `isOn` in state and runs `useEffect(() => onChange(isOn), [isOn, onChange])` so its parent hears about every flip. What is the simpler design?
Q3. Four effects from a code review. Which one is keeping, not deleting?
Practice only: not graded, not saved, not evidence.

07. Apply it

Audit one component from the book-search practice project (or any project of yours):

  1. List every effect and classify it: external synchronisation, event logic in disguise, or derived value.
  2. Delete the derived-value effects and compute during render; move disguised event logic into its handler.
  3. Add a render counter like the one in this lesson and compare before and after.
  4. 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.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check