ReactMedium

Cleanup issues?

Cleanup issues happen when effects or refs set something up but do not fully undo it, or undo the wrong thing. Symptoms include duplicated event handlers, timers that keep running after a component unmounts, requests updating the wrong screen, memory leaks, and bugs that appear only in development under Strict Mode. Every effect that subscribes, schedules or connects must return a symmetric cleanup.

Typical mistakes

  1. No cleanup at all for listeners, intervals, sockets or observers.
  2. Removing a different function: removeEventListener("resize", () => update()) creates a new function, so nothing is removed. Keep a reference to the same function.
  3. Different options: a listener added with { capture: true } must be removed with the same capture flag.
  4. Cleanup using values from the wrong render: reading ref.current in cleanup when it may have changed; copy it to a variable inside the effect.
  5. Not aborting fetches: results arrive after navigation or for an outdated input.
  6. Async cleanup: cleanups must be synchronous; start async teardown but do not await it in the cleanup.
  7. Third-party instances (maps, charts, players) not destroyed, so a second instance is created on remount.
  8. Fighting Strict Mode with "run once" refs instead of making setup and cleanup symmetric.

Checks

  • Mount, unmount and remount the component (Strict Mode does this in development; <Activity> does it when hiding and showing). Nothing should duplicate or break.
  • Watch listener counts and heap size in Chrome DevTools.

React 19 helps

Ref callbacks can return cleanup functions, so observers and libraries attached to DOM nodes can be cleaned up next to where they are set up.

Code example

tsx
1import { useEffect, useRef } from "react";
2
3export function Chart({ data }: { data: number[] }) {
4 const containerRef = useRef<HTMLDivElement>(null);
5
6 useEffect(() => {
7 const el = containerRef.current; // copy: the ref may change before cleanup runs
8 if (!el) return;
9
10 const onResize = () => console.log("resize", el.clientWidth); // keep the SAME function reference
11 window.addEventListener("resize", onResize, { passive: true });
12
13 const controller = new AbortController();
14 fetch("/api/annotations", { signal: controller.signal }).catch(() => {});
15
16 const chart = createChart(el, data); // third-party instance
17
18 return () => {
19 window.removeEventListener("resize", onResize); // same reference, same options
20 controller.abort();
21 chart.destroy(); // avoid a second chart on remount
22 };
23 // Wrong: window.removeEventListener("resize", () => onResize()); // different function, nothing removed
24 }, [data]);
25
26 return <div ref={containerRef} style={{ height: 240 }} />;
27}
28
29declare function createChart(el: HTMLElement, data: number[]): { destroy(): void };

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app