Skip to content

Cleanup ​

Everything a useEffect starts must be stopped by its cleanup function. Unremoved window/document listeners, intervals, and observers leak memory and duplicate immediately under React StrictMode's development double-mount.

In short

  • Always return a teardown function: pair every addEventListener, setInterval, and observer inside useEffect with its matching removal.
  • Checked statically: listener-cleanup flags effects that register subscriptions without cleaning them up.

Listeners and intervals without a cleanup return are rejected (listener-cleanup):

✕ Rejectedlistener-cleanup
tsx
import { useEffect, useState } from "react";

export function Clock() {
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const tick = (): void => setNow(new Date());
    const timer = setInterval(tick, 1000);
    window.addEventListener("focus", tick);
    console.log("started", timer);
  }, []);
  return <p>{now.toLocaleTimeString()}</p>;
}

✅ Accepted: the effect returns a function that undoes it

✓ Accepted0 diagnostics
tsx
import { useEffect, useState } from "react";

export function Clock() {
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const tick = (): void => setNow(new Date());
    const timer = setInterval(tick, 1000);
    window.addEventListener("focus", tick);
    return () => {
      clearInterval(timer);
      window.removeEventListener("focus", tick);
    };
  }, []);
  return <p>{now.toLocaleTimeString()}</p>;
}

A listener written in place (addEventListener("focus", () => ...)) can't be removed at all, since removing needs the same function: keep it in a const, or pass { signal } from an AbortController the cleanup aborts.

What counts as stopping: the effect returns a function (or a name bound to one). A listener added with { signal } needs no cleanup of its own, and neither does one with { once: true } on an object that goes away with the component; on window, document, navigator or a matchMedia(...) list, once ends it only if the event comes, so it needs the cleanup or a signal too (listener-cleanup). Observers (ResizeObserver, IntersectionObserver, MutationObserver, PerformanceObserver) count as stopped when the effect calls .disconnect().

What the rule can't see: whether the cleanup it found stops this listener (any returned function counts), and listeners added by a function the effect calls.

Rules on this page: listener-cleanup

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra