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
- No cleanup at all for listeners, intervals, sockets or observers.
- Removing a different function:
removeEventListener("resize", () => update())creates a new function, so nothing is removed. Keep a reference to the same function. - Different options: a listener added with
{ capture: true }must be removed with the same capture flag. - Cleanup using values from the wrong render: reading
ref.currentin cleanup when it may have changed; copy it to a variable inside the effect. - Not aborting fetches: results arrive after navigation or for an outdated input.
- Async cleanup: cleanups must be synchronous; start async teardown but do not
awaitit in the cleanup. - Third-party instances (maps, charts, players) not destroyed, so a second instance is created on remount.
- 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";23export function Chart({ data }: { data: number[] }) {4 const containerRef = useRef<HTMLDivElement>(null);56 useEffect(() => {7 const el = containerRef.current; // copy: the ref may change before cleanup runs8 if (!el) return;910 const onResize = () => console.log("resize", el.clientWidth); // keep the SAME function reference11 window.addEventListener("resize", onResize, { passive: true });1213 const controller = new AbortController();14 fetch("/api/annotations", { signal: controller.signal }).catch(() => {});1516 const chart = createChart(el, data); // third-party instance1718 return () => {19 window.removeEventListener("resize", onResize); // same reference, same options20 controller.abort();21 chart.destroy(); // avoid a second chart on remount22 };23 // Wrong: window.removeEventListener("resize", () => onResize()); // different function, nothing removed24 }, [data]);2526 return <div ref={containerRef} style={{ height: 240 }} />;27}2829declare 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.