Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 06 / Stage 2

useEffect and side effects

Goal: Tell a side effect apart from a plain render-time calculation, write your first useEffect, use the dependency array correctly - including the stale-closure bug you get from leaving a value out of it - write a cleanup function and know exactly what it is protecting against, recognize the single most common effect mistake (using an effect to hold a value you could have just computed), see what React's StrictMode double-invoke in development is actually proving, and know when a side effect is the wrong tool entirely. Time: ~5 hours · Level: comfortable with useState, event handlers, and lifting state up (Part 3)

What you will learn

  • What counts as a side effect (synchronizing with something outside React: the DOM, a timer, a subscription, document.title) and what does not (anything computable from props/state you already have)
  • useEffect's shape: a function that runs after render, an optional cleanup function it can return, and a dependency array that controls when it reruns
  • The dependency array's one real job - not "performance," but correctness: which values the effect actually reads determine when it must rerun, or it keeps using stale ones
  • Cleanup functions: why a repeating timer or an event listener started inside an effect has to be torn down, and what breaks when it isn't
  • The effects-for-derived-state anti-pattern - this course's single most emphasized effect mistake, deliberately kept separate from performance tuning (Part 12 profiles a genuinely slow list before reaching for memoization at all - this part is effects only)
  • What React's StrictMode double-invoke in development is actually checking for, and why it is not a bug
  • When an effect is the wrong tool: a user-triggered side effect (a click) belongs in its event handler, not routed through a state flag and an effect
  • This part's running examples: an order-status tab title, a live clock, a delivery-radius watcher, a train search, a price-watch subscription widget, and an add-to-cart logger

A note on how this part is organised: same convention as Parts 1-5 - every examples/ and solutions/ file here is wired into this repo's own harness/ and actually executed before being shown below. When you build along, type the code into your own project; this repo's copy is the verified reference, not something you need to open.

Topics in this part

Practice

Every exercise below is a React component (or a Broken/Fixed pair) in its own .jsx file, paired with a .test.jsx that actually renders and interacts with it using Testing Library/Vitest - the same verified-output rule as every example in this course. Exercises involving timers use vi.useFakeTimers(), the same way examples/02_live_clock_cleanup.jsx does.


Exercise 1: A first effect - synchronize the tab title with a cart count

Scenario: A Blinkit-style cart screen wants the browser tab to show how many items are in the cart, even while the shopper is looking at a different tab. What to do: Write CartTabTitle() with an itemCount piece of state starting at 0, an "Add item" button that increments it, and a useEffect that sets document.title to Cart (${itemCount}) whenever itemCount changes.

Sample output (really run):

initial render       -> document.title: "Cart (0)"
click "Add item" once -> document.title: "Cart (1)"
click "Add item" again -> document.title: "Cart (2)"

💡 Hint: this is examples/01_document_title_sync.jsx's OrderStatusTab shape exactly - one piece of state, one effect that writes to document.title, with that state in the dependency array.


Exercise 2: Cleanup - a "typing..." indicator that clears itself

Scenario: A WhatsApp-style chat box shows "Priya is typing..." for 2 seconds after each keystroke, then clears it - but only if no new keystroke arrives first. What to do: Write TypingIndicator() with a text input, an isTyping boolean state, and a keystrokeCount number state. Every keystroke increments keystrokeCount; a useEffect keyed on keystrokeCount (not on isTyping - setting a boolean to a value it already holds is not a change React will re-render for) sets isTyping to true and starts a 2-second setTimeout that sets it back to false, returning a cleanup function that clears that timeout (so a fast second keystroke cancels the first timer instead of racing it).

Sample output (vi.useFakeTimers(), really run):

type one character          -> "Priya is typing..."
advance fake time by 1000ms -> still "Priya is typing..." (timer not done yet)
type another character      -> still "Priya is typing..." (timer restarted)
advance fake time by 2000ms -> "" (timer from the second keystroke finished)

💡 Hint: the effect's cleanup function is () => clearTimeout(timeoutId), the same shape as examples/02_live_clock_cleanup.jsx's clearInterval - except here the cleanup runs on every keystroke (because isTyping flips back to true each time), not just on unmount.


Exercise 3: Find and fix a missing-dependency bug

Scenario: A Zomato-style price-drop watcher listens for a "price-update" event and should alert the shopper only once the price drops to or below their configured targetPrice. A teammate wrote:

export function PriceAlertBroken({ targetPrice, onAlert }) {
  useEffect(() => {
    function handleUpdate(event) {
      if (event.detail.newPrice <= targetPrice) {
        onAlert(event.detail.newPrice);
      }
    }
    window.addEventListener("price-update", handleUpdate);
    return () => window.removeEventListener("price-update", handleUpdate);
  }, []);
  return <p>Watching for a price at or below ₹{targetPrice}</p>;
}

Testers report that raising their target price after the watcher is already running has no effect - updates that should now trigger an alert are silently ignored. What to do: Write both PriceAlertBroken (the code above, unchanged) and PriceAlertFixed, where only the fixed version's effect re-subscribes with the current targetPrice. Dispatch a "price-update" custom event the same way examples/03_dependency_array_missing_deps.jsx does, to drive your test.

Sample output (really run - mount with targetPrice=500, then rerender with targetPrice=800 before dispatching a price update of 600):

PriceAlertBroken: onAlert is never called (still comparing against 500, closed over at mount)
PriceAlertFixed:  onAlert(600) is called (compares against the current targetPrice, 800)

💡 Hint: this is examples/03_dependency_array_missing_deps.jsx's exact bug, renamed - add targetPrice to the dependency array so the effect (and the closure inside it) is rebuilt every time it changes.


Exercise 4: Find and fix an effect-for-derived-state bug

Scenario: An expense-tracker screen (the same domain as this course's upcoming Stage 2 project) shows a running total for a list of expenses. A teammate wrote:

export function ExpenseTotalViaEffect({ expenses }) {
  const [total, setTotal] = useState(0);
  useEffect(() => {
    setTotal(expenses.reduce((sum, e) => sum + e.amount, 0));
  }, [expenses]);
  return <p>Total: ₹{total}</p>;
}

It shows the right number eventually, but a reviewer flagged it as needing an unnecessary extra render on every single expense-list change. What to do: Write both ExpenseTotalViaEffect (the code above, unchanged, with a render counter added the same way examples/04_derived_state_antipattern.jsx does) and ExpenseTotalDuringRender, which computes the same total as a plain variable during render, no useState/useEffect at all.

Sample output (really run, expenses changes once after mount):

ExpenseTotalViaEffect:      renders twice per expenses change (render, then the effect's setState)
ExpenseTotalDuringRender:   renders once per expenses change
both show the same total: "Total: ₹450"

💡 Hint: this part's Section 5 names the rule directly - if a value can be computed from props/state you already have, compute it, don't copy it into its own state and "keep it in sync" with an effect.


Exercise 5: Prove a cleanup function survives StrictMode's double-invoke

Scenario: A notifications widget must register exactly one "online"/"offline" pair of listeners while mounted, no matter how many times development-mode StrictMode mounts, unmounts, and remounts it to check for a missing cleanup function. What to do: Write ConnectionStatusWidget({ onStatusChange }) with a useEffect that calls onStatusChange("online") on mount via a (fake, for this course) registerConnectionListener(callback) helper you also write, returning a cleanup function that calls the matching unregisterConnectionListener(callback). Render it inside <StrictMode> and confirm, from the outside, exactly how many listeners are registered after the double-mount settles.

Sample output (really run, the same StrictMode technique as examples/05_strict_mode_double_invoke.jsx):

render inside StrictMode, after settling:
  registerConnectionListener was called twice (mount, cleanup, mount again)
  unregisterConnectionListener was called once (the cleanup between the two mounts)
  exactly one listener remains active - no duplicate, no leak

💡 Hint: register/unregister in a small in-memory Set inside your helper module, and assert listeners.size === 1 after render settles - that is the real proof StrictMode's double-invoke did not leave a duplicate subscription behind.


Exercise 6: Refactor a click-triggered effect into a plain event handler

Scenario: A wishlist screen is supposed to show a "Saved!" notice for exactly one second after the shopper clicks a heart icon. A teammate's version uses a flag-plus-effect, the same broken shape as examples/06_effect_vs_handler_for_events.jsx:

export function WishlistNoticeBroken({ onShowNotice }) {
  const [justSaved, setJustSaved] = useState(false);
  useEffect(() => {
    if (justSaved) onShowNotice();
  }, [justSaved, onShowNotice]);
  return <button onClick={() => setJustSaved(true)}>♡ Save</button>;
}

What to do: Write both WishlistNoticeBroken (unchanged above) and WishlistNoticeFixed, which deletes the state/effect entirely and calls onShowNotice() directly inside the button's onClick. Prove, the same way examples/06_effect_vs_handler_for_events.test.jsx does, that clicking the broken version twice in a row only shows the notice once, while the fixed version shows it every time.

Sample output (really run, three clicks on each):

WishlistNoticeBroken: onShowNotice called 1 time total (stuck after the first click)
WishlistNoticeFixed:  onShowNotice called 3 times total (once per click)

💡 Hint: setJustSaved(true) when justSaved is already true is not a change at all, so React skips the re-render and the effect never runs again - exactly this part's Section 7 rule: a click is already an event, it does not need an effect to notice it happened.

Show the solutions for Part 6 (12 files)

solutions/ex01_cart_tab_title.jsx

// Exercise 1 solution: one piece of state, one effect that writes to
// document.title - the same shape as the lesson's OrderStatusTab.
import { useEffect, useState } from "react";

export function CartTabTitle() {
  const [itemCount, setItemCount] = useState(0);

  useEffect(() => {
    document.title = `Cart (${itemCount})`;
  }, [itemCount]);

  return (
    <div>
      <p>Items in cart: {itemCount}</p>
      <button onClick={() => setItemCount((current) => current + 1)}>Add item</button>
    </div>
  );
}

solutions/ex01_cart_tab_title.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { CartTabTitle } from "./ex01_cart_tab_title.jsx";

describe("CartTabTitle keeps document.title in sync with itemCount", () => {
  it("really updates the tab title on every click", async () => {
    const user = userEvent.setup();
    render(<CartTabTitle />);

    expect(document.title).toBe("Cart (0)");

    const button = screen.getByRole("button", { name: "Add item" });
    await user.click(button);
    expect(document.title).toBe("Cart (1)");
    expect(screen.getByText("Items in cart: 1")).toBeInTheDocument();

    await user.click(button);
    expect(document.title).toBe("Cart (2)");
  });
});

solutions/ex02_typing_indicator.jsx

// Exercise 2 solution.
//
// A plain boolean isTyping cannot be the effect's dependency: setting it to
// true when it is *already* true is not a change, so React would skip the
// re-render and the effect - and its timer - would never restart on a fast
// second keystroke. keystrokeCount instead changes on every keystroke, no
// matter what isTyping currently is, so the effect (and its cleanup, which
// clears the *previous* timer) really does run again each time.
import { useEffect, useState } from "react";

export function TypingIndicator() {
  const [text, setText] = useState("");
  const [isTyping, setIsTyping] = useState(false);
  const [keystrokeCount, setKeystrokeCount] = useState(0);

  // oxlint's react(set-state-in-effect) warns here on purpose: this is a
  // legitimate use, not Part 6 Section 5's anti-pattern - isTyping is not
  // computable from keystrokeCount during render, it is synchronized with
  // a real timer (an outside system), which is exactly what an effect is for.
  useEffect(() => {
    if (keystrokeCount === 0) return;

    setIsTyping(true);
    const timeoutId = setTimeout(() => setIsTyping(false), 2000);
    return () => clearTimeout(timeoutId);
  }, [keystrokeCount]);

  return (
    <div>
      <input
        value={text}
        onChange={(event) => {
          setText(event.target.value);
          setKeystrokeCount((current) => current + 1);
        }}
      />
      <p>{isTyping ? "Priya is typing..." : ""}</p>
    </div>
  );
}

solutions/ex02_typing_indicator.test.jsx

import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TypingIndicator } from "./ex02_typing_indicator.jsx";

beforeEach(() => {
  vi.useFakeTimers();
});

afterEach(() => {
  vi.useRealTimers();
});

describe("TypingIndicator clears itself after 2s of no new keystroke", () => {
  it("really restarts the timer on a fast second keystroke instead of racing it", () => {
    render(<TypingIndicator />);
    const input = screen.getByRole("textbox");

    fireEvent.change(input, { target: { value: "h" } });
    expect(screen.getByText("Priya is typing...")).toBeInTheDocument();

    act(() => {
      vi.advanceTimersByTime(1000);
    });
    expect(screen.getByText("Priya is typing...")).toBeInTheDocument();

    fireEvent.change(input, { target: { value: "hi" } });
    // The second keystroke's effect cleared the first timer and started a
    // fresh 2-second one - 1000ms more (2000ms since keystroke 1) should
    // NOT clear it yet.
    act(() => {
      vi.advanceTimersByTime(1000);
    });
    expect(screen.getByText("Priya is typing...")).toBeInTheDocument();

    act(() => {
      vi.advanceTimersByTime(1000);
    });
    expect(screen.queryByText("Priya is typing...")).not.toBeInTheDocument();
  });
});

solutions/ex03_price_alert.jsx

// Exercise 3 solution: same bug and fix as examples/03_dependency_array_missing_deps.jsx,
// renamed for a price-drop watcher.
//
// oxlint's react/only-export-components rule warns below because this
// file also exports a small test helper (dispatchPriceUpdate) alongside
// the two components - expected and left as a warning on purpose.
import { useEffect } from "react";

export function PriceAlertBroken({ targetPrice, onAlert }) {
  useEffect(() => {
    function handleUpdate(event) {
      if (event.detail.newPrice <= targetPrice) {
        onAlert(event.detail.newPrice);
      }
    }
    window.addEventListener("price-update", handleUpdate);
    return () => window.removeEventListener("price-update", handleUpdate);
    // BUG: targetPrice is read inside handleUpdate but missing here, so a
    // later targetPrice prop change never reaches this closure. oxlint's
    // react-hooks/exhaustive-deps rule correctly flags this - left visible
    // and documented, the same as examples/03's missing-deps bug, instead
    // of silenced, since this file exists to show exactly this mistake.
  }, []);

  return <p>Watching for a price at or below ₹{targetPrice}</p>;
}

export function PriceAlertFixed({ targetPrice, onAlert }) {
  useEffect(() => {
    function handleUpdate(event) {
      if (event.detail.newPrice <= targetPrice) {
        onAlert(event.detail.newPrice);
      }
    }
    window.addEventListener("price-update", handleUpdate);
    return () => window.removeEventListener("price-update", handleUpdate);
  }, [targetPrice, onAlert]);

  return <p>Watching for a price at or below ₹{targetPrice}</p>;
}

export function dispatchPriceUpdate(newPrice) {
  window.dispatchEvent(new CustomEvent("price-update", { detail: { newPrice } }));
}

solutions/ex03_price_alert.test.jsx

import { act, render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { PriceAlertBroken, PriceAlertFixed, dispatchPriceUpdate } from "./ex03_price_alert.jsx";

describe("PriceAlertBroken ignores a raised target set after mount", () => {
  it("really never alerts because its listener still closes over the original targetPrice", () => {
    const onAlert = vi.fn();
    const { rerender } = render(<PriceAlertBroken targetPrice={500} onAlert={onAlert} />);

    rerender(<PriceAlertBroken targetPrice={800} onAlert={onAlert} />);
    act(() => dispatchPriceUpdate(600));

    expect(onAlert).not.toHaveBeenCalled();
  });
});

describe("PriceAlertFixed re-subscribes with the current targetPrice", () => {
  it("really alerts once the target has been raised past the new price", () => {
    const onAlert = vi.fn();
    const { rerender } = render(<PriceAlertFixed targetPrice={500} onAlert={onAlert} />);

    rerender(<PriceAlertFixed targetPrice={800} onAlert={onAlert} />);
    act(() => dispatchPriceUpdate(600));

    expect(onAlert).toHaveBeenCalledWith(600);
  });
});

solutions/ex04_expense_total.jsx

// Exercise 4 solution: same shape as examples/04_derived_state_antipattern.jsx -
// a value fully derivable from props should be computed during render, not
// copied into its own state and "kept in sync" with an effect.
//
// oxlint flags two things below, both on purpose, same as examples/04:
// react(set-state-in-effect) on ExpenseTotalViaEffect's effect (that call
// IS the anti-pattern this exercise asks you to fix) and react(refs) on
// every renderCountRef.current read/write during render (a measurement
// tool for this lesson, not a pattern for real component code).
import { useEffect, useRef, useState } from "react";

export function ExpenseTotalViaEffect({ expenses }) {
  const renderCountRef = useRef(0);
  renderCountRef.current += 1;

  const [total, setTotal] = useState(0);

  useEffect(() => {
    setTotal(expenses.reduce((sum, expense) => sum + expense.amount, 0));
  }, [expenses]);

  return (
    <div>
      <p>Total: ₹{total}</p>
      <p>Render count: {renderCountRef.current}</p>
    </div>
  );
}

export function ExpenseTotalDuringRender({ expenses }) {
  const renderCountRef = useRef(0);
  renderCountRef.current += 1;

  const total = expenses.reduce((sum, expense) => sum + expense.amount, 0);

  return (
    <div>
      <p>Total: ₹{total}</p>
      <p>Render count: {renderCountRef.current}</p>
    </div>
  );
}

solutions/ex04_expense_total.test.jsx

import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { ExpenseTotalDuringRender, ExpenseTotalViaEffect } from "./ex04_expense_total.jsx";

const INITIAL = [{ amount: 100 }, { amount: 50 }];
const UPDATED = [{ amount: 100 }, { amount: 50 }, { amount: 300 }];

describe("ExpenseTotalViaEffect gets the right total, with a wasted extra render", () => {
  it("really renders twice per expenses change", () => {
    const { rerender } = render(<ExpenseTotalViaEffect expenses={INITIAL} />);
    expect(screen.getByText("Render count: 2")).toBeInTheDocument();

    rerender(<ExpenseTotalViaEffect expenses={UPDATED} />);
    expect(screen.getByText("Total: ₹450")).toBeInTheDocument();
    expect(screen.getByText("Render count: 4")).toBeInTheDocument();
  });
});

describe("ExpenseTotalDuringRender gets the same total with no wasted render", () => {
  it("really renders exactly once per expenses change", () => {
    const { rerender } = render(<ExpenseTotalDuringRender expenses={INITIAL} />);
    expect(screen.getByText("Render count: 1")).toBeInTheDocument();

    rerender(<ExpenseTotalDuringRender expenses={UPDATED} />);
    expect(screen.getByText("Total: ₹450")).toBeInTheDocument();
    expect(screen.getByText("Render count: 2")).toBeInTheDocument();
  });
});

solutions/ex05_connection_status_widget.jsx

// Exercise 5 solution.
//
// listeners is a module-level Set standing in for a real browser/network
// API's own internal subscriber list - this course fakes it rather than
// touching a real connection, the same "fake it locally" rule used for any
// data-ish example before Part 11.
//
// oxlint's react/only-export-components rule warns below because this
// file exports plain helper functions alongside the one component -
// expected and left as a warning on purpose, the same as every hook file
// in Part 7.
import { useEffect } from "react";

const listeners = new Set();

export function registerConnectionListener(callback) {
  listeners.add(callback);
}

export function unregisterConnectionListener(callback) {
  listeners.delete(callback);
}

export function activeListenerCount() {
  return listeners.size;
}

export function ConnectionStatusWidget({ onStatusChange }) {
  useEffect(() => {
    registerConnectionListener(onStatusChange);
    onStatusChange("online");

    return () => unregisterConnectionListener(onStatusChange);
  }, [onStatusChange]);

  return <p>Watching connection status</p>;
}

solutions/ex05_connection_status_widget.test.jsx

import { render } from "@testing-library/react";
import { StrictMode } from "react";
import { describe, expect, it, vi } from "vitest";
import { ConnectionStatusWidget, activeListenerCount } from "./ex05_connection_status_widget.jsx";

describe("ConnectionStatusWidget's cleanup survives StrictMode's double-invoke", () => {
  it("really ends up with exactly one active listener, with onStatusChange called twice total", () => {
    const onStatusChange = vi.fn();

    render(
      <StrictMode>
        <ConnectionStatusWidget onStatusChange={onStatusChange} />
      </StrictMode>,
    );

    // mount, cleanup, mount again - register ran twice, unregister ran once
    // in between, so exactly one listener is left registered.
    expect(onStatusChange).toHaveBeenCalledTimes(2);
    expect(activeListenerCount()).toBe(1);
  });
});

solutions/ex06_wishlist_notice.jsx

// Exercise 6 solution: same bug and fix as examples/06_effect_vs_handler_for_events.jsx -
// a click is already an event; it never needed a state flag and an effect
// to be noticed.
import { useEffect, useState } from "react";

export function WishlistNoticeBroken({ onShowNotice }) {
  const [justSaved, setJustSaved] = useState(false);

  useEffect(() => {
    if (justSaved) {
      onShowNotice();
    }
    // BUG: justSaved is never reset to false, so a second click's
    // setJustSaved(true) is not a change React re-renders for.
  }, [justSaved, onShowNotice]);

  return <button onClick={() => setJustSaved(true)}>♡ Save</button>;
}

export function WishlistNoticeFixed({ onShowNotice }) {
  return <button onClick={() => onShowNotice()}>♡ Save</button>;
}

solutions/ex06_wishlist_notice.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { WishlistNoticeBroken, WishlistNoticeFixed } from "./ex06_wishlist_notice.jsx";

describe("WishlistNoticeBroken only shows the notice once, no matter how many clicks follow", () => {
  it("really stays stuck after the first click", async () => {
    const user = userEvent.setup();
    const onShowNotice = vi.fn();
    render(<WishlistNoticeBroken onShowNotice={onShowNotice} />);

    const button = screen.getByRole("button", { name: "♡ Save" });
    await user.click(button);
    await user.click(button);
    await user.click(button);

    expect(onShowNotice).toHaveBeenCalledTimes(1);
  });
});

describe("WishlistNoticeFixed shows the notice on every click, with no effect at all", () => {
  it("really calls onShowNotice once per click", async () => {
    const user = userEvent.setup();
    const onShowNotice = vi.fn();
    render(<WishlistNoticeFixed onShowNotice={onShowNotice} />);

    const button = screen.getByRole("button", { name: "♡ Save" });
    await user.click(button);
    await user.click(button);
    await user.click(button);

    expect(onShowNotice).toHaveBeenCalledTimes(3);
  });
});

Common mistakes

Mistake Why it is wrong Fix
Writing to document.title, starting a timer, or touching localStorage directly in the render body Mixes a side effect into what is supposed to be a pure calculation - React may call the render body more than once per visible update, including under StrictMode Put it inside useEffect, which React guarantees runs after render, not during it (Section 1-2)
Leaving a prop or state value out of the dependency array even though the effect's code reads it The effect's inner functions close over whatever that value was when the effect last ran - a later change to the real value never reaches the stale closure List every value the effect's body actually reads in the dependency array, so React rebuilds the closure when any of them changes (Section 4)
Copying a prop/state-derivable value into its own useState, then writing a useEffect to "keep it in sync" Gets the right answer, but costs a second, entirely avoidable render every time the source value changes, for no benefit If a value can be computed from props/state you already have, compute it as a plain variable during render - no useState, no effect (Section 5)
Assuming StrictMode's double mount/unmount/remount in development is a bug in your code or in React It is deliberate - its only job is to make a missing-cleanup mistake fail loudly in development instead of silently in production Treat a StrictMode double-call as the test it is: if the second mount behaves wrong (duplicate subscription, doubled timer), the cleanup function is incomplete, not React (Section 6)
Using a state flag plus an effect to react to a button click A flag that is already true cannot become true again - that is not a change, so React skips the rerender, and the effect silently never runs on the second occurrence Handle a user-triggered action directly in its event handler - it is already the right moment, no effect needed (Section 7)
Forgetting a cleanup function for anything an effect starts that doesn't stop on its own (setInterval, addEventListener, a subscription) The subscription/timer keeps running against a component instance that no longer exists, for as long as the page stays open - a real memory/CPU leak Return a function from the effect that undoes exactly what the setup did (clearInterval, removeEventListener) (Section 3)

Quick recap

  • A side effect synchronizes a component with something outside React (the DOM, a timer, a subscription); anything computable from props/state you already have is a plain render-time calculation, never an effect.
  • useEffect(setup, deps) runs its setup function after render, reruns it whenever a value listed in deps changes, and calls whatever setup returned (the cleanup function) right before that rerun and again on unmount.
  • The dependency array's job is correctness, not performance: every value the effect's body actually reads belongs in it, or that closure goes stale the moment the real value changes.
  • Anything an effect starts that doesn't stop on its own - a timer, a listener, a subscription - needs a cleanup function that undoes exactly what the setup did, or it leaks for as long as the page stays open.
  • Reaching for useState + useEffect to hold a value you could have computed directly during render costs a real, provable extra render for no benefit - this is the mistake this part emphasizes most, kept deliberately separate from the performance hooks taught much later in Part 12.
  • StrictMode's development-only double mount/cleanup/mount is deliberate, not a bug - it exists to make a missing or incomplete cleanup function fail loudly in development, instead of quietly in production.
  • A user-triggered side effect (a click, a submit) belongs directly in its event handler - routing it through a state flag and an effect adds a real bug (a flag that's already true can't "become true" again) for no benefit.

Checklist

  • I can say, in one sentence, what makes something a side effect instead of a plain render-time calculation.
  • I wrote an effect that writes to document.title (or an equivalent outside-React target), with the correct dependency array.
  • I reproduced the stale-closure bug myself - left a value an effect's closure reads out of the dependency array, watched a later prop change get silently ignored - then fixed it by adding that value to the array.
  • I wrote (or found) an effect that starts something ongoing, and gave it a cleanup function that actually undoes the setup - and proved, the way examples/02_live_clock_cleanup.test.jsx does, that the ongoing thing really stops.
  • I reproduced the effects-for-derived-state mistake myself - copied a computable value into useState and "synced" it with an effect - and proved the extra render with a render counter, then deleted the useState/useEffect pair entirely.
  • I rendered a component inside <StrictMode> and watched its effect's setup and cleanup run in the mount-cleanup-mount pattern, and I can explain why that is intentional.
  • I found (or wrote) a case of a click routed through a state flag and an effect, reproduced the "second click does nothing" bug, and fixed it by moving the logic directly into the click handler.

Search the guide