Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 132 ยท Hooks

Cleanup, Subscriptions and Timers

Learn how useEffect cleanup works in React - intervals, event listeners, subscriptions, AbortController, race conditions and the StrictMode setup, cleanup, setup cycle, with runnable logs.

Every effect that starts something must also know how to stop it. A timer keeps ticking after its component is gone, a listener keeps calling a function that closes over old values, a subscription keeps a connection open, and a slow network answer arrives after the user has moved on. The cleanup function is how an effect tells React "here is how to undo what I just did".

This lesson goes through the most common resources an effect owns: timers, event listeners, subscriptions and in-flight requests. For each one you will see the leak or bug that appears without cleanup, and the version that stays correct. It builds on Effects with useEffect and Effect Dependencies.

The contract: setup and cleanup are a pair

An effect may return a function. React calls it:

  1. Before the effect runs again, with the values from the render that created it.
  2. When the component unmounts.

Write cleanup as the exact mirror of setup. Whatever your setup acquired (a timer id, a listener function, a connection object), the cleanup releases by using the same reference. Then, from the effect's point of view, it does not matter how often React runs the pair: each cycle starts clean and ends clean.

TEXT
render A -> commit -> setup(A)
render B -> commit -> cleanup(A) -> setup(B)
unmount   ->          cleanup(B)

Cleanup is not reserved for the moment the page closes: it runs whenever React removes the component or re-synchronizes the effect. That is the whole lifecycle, and everything below is an instance of it.

Timers: setInterval and setTimeout

A countdown is the simplest timer that must be cleaned up. We use a 30 ms tick in the demo so you can see it finish quickly.

A countdown that cleans up its interval

Wait for the countdown to finish and the paragraph reads Liftoff!. The log shows start interval once and reached zero when the count gets there. The interval itself keeps ticking below zero, because nothing else stops it; only unmounting does. Press "Remove countdown" at any time and the console shows clear interval: the cleanup stopped the timer, so nothing is updated afterward.

Two details worth copying. First, the interval uses a functional update (value => value - 1), so the effect does not read remaining and can have an empty array: the timer is created once. Second, the id is a local const captured by the cleanup, never a variable shared across renders.

setTimeout needs the same treatment. A timeout that fires after unmount will call a setter on a gone component. React no longer warns about this, but the work is still wasted and the timer can keep objects alive. Store the id and call clearTimeout in the cleanup.

Event listeners

Adding a listener to something that outlives your component (the window, the document, a media query) is a subscription. Without cleanup, every mount adds another listener and old ones keep running.

To make the leak visible we use a tiny hand-written event bus. It counts how many listeners are attached, just as the browser would internally.

Counting attached listeners

Do this: press "Mount Leaky", then "Unmount", then "Mount Leaky" again, and then "Emit ping". The console prints leaky heard: ping twice, once from a component that no longer exists, and "Active listeners" shows 2. (The number is read during render, so it can lag one render behind the effects; the bus is not React state, and "Emit ping" forces a refresh.) Now press "Mount Tidy" and "Unmount": the count goes back to what it was before.

For real DOM listeners the same rule applies, with one trap: removeEventListener only works with the same function reference and the same options. That is why the handler is declared as a named constant inside the effect.

JSX
useEffect(() => {
  function handleResize() {
    setWidth(window.innerWidth);
  }
  window.addEventListener('resize', handleResize);
  return () => window.removeEventListener('resize', handleResize);
}, []);

If you pass { capture: true } to addEventListener, pass it to removeEventListener as well, or the listener stays attached. An AbortController signal gives a tidier alternative: addEventListener('resize', handler, { signal }) and controller.abort() in the cleanup removes every listener registered with that signal.

Subscriptions to external sources

Sockets, BroadcastChannel, IntersectionObserver, matchMedia and third-party stores all follow the same "subscribe, return unsubscribe" shape. Many libraries return the unsubscribe function directly, so the effect can return it as is:

JSX
useEffect(() => {
  const unsubscribe = store.subscribe(() => setSnapshot(store.getSnapshot()));
  return unsubscribe;
}, []);

Do be careful about one thing: return the function, do not call it. return unsubscribe() would unsubscribe immediately and return undefined. For subscribing to external state in particular, React has a purpose-built hook that is safer than this pattern, useSyncExternalStore; see External Stores.

StrictMode: setup, cleanup, setup

In development, when you wrap your app in <StrictMode>, React deliberately runs every effect an extra time right after the first mount: setup, then cleanup, then setup again. It does this to prove that your cleanup really reverses your setup. If a leak or a duplicate-connection bug exists, you see it immediately instead of in production.

Watching StrictMode run the cycle twice

On first load the console shows connect general (open: 1), disconnect general (open: 0), connect general (open: 1). The count ends at 1, so the cleanup is correct. Now remove the return from connect in your head: the count would climb to 2 and stay there. That is the bug StrictMode exists to expose. Pressing "music" shows the normal single cycle (disconnect general, connect music): the extra cycle happens only on mount. In production builds it never happens.

The wrong reaction to the double run is to add a useRef flag so the effect only runs once. Fix the cleanup instead. If the effect must not repeat in real life (for example, sending an analytics event), ask whether it is really a synchronization at all; it is usually an event ("the user visited this page") and belongs in a handler or can tolerate being deduplicated.

Fetching and race conditions

The trickiest resource to clean up is a request that is still in flight. Imagine a profile page: the user clicks Alice, then immediately Bob. Two requests are running. If Bob's answer arrives first and Alice's later, a naive effect saves Bob's data and then overwrites it with Alice's, and the screen is wrong for the id the user last chose. That is a race condition.

The demo uses a fake network: fetchUser(id) answers after a delay that differs per user (Alice is slow, Bob is fast). A checkbox switches the protection on or off.

A race condition and its fix

With the checkbox off, press "Alice" and then, within 120 ms, "Bob". The paragraph ends up saying Requested: bob. Showing: Profile of alice. The slow, older answer arrived last and won. Tick the box and repeat: the console now logs ignored a stale answer for alice and the screen is right.

The mechanism is the cleanup. When id changes, React runs the cleanup of the previous effect, which flips that closure's own ignore flag to true. The old promise callback still runs, but it sees its own flag and does nothing. Each effect run has its own flag, so no run can disturb another.

This ignore flag makes the result harmless. It does not stop the network work. To actually cancel the request, use an AbortController.

Cancelling with AbortController

fetch accepts a signal. Calling controller.abort() rejects the promise with an AbortError and tells the browser to drop the request. A cleanup is the natural place to call it. Our sandbox cannot reach real servers, so this demo uses a hand-written wait(ms, signal) helper that behaves the same way as a signal-aware fetch:

Aborting the previous request in cleanup

Type re one character at a time and then wait. You get aborted: r followed by finished: re. The request for r never completes; the cleanup cancelled it before the next setup started.

Notice the catch branch: an abort is not an error, so you must filter AbortError before showing a failure message. With a real fetch the code is the same, fetch(url, { signal: controller.signal }).

Which should you use, the ignore flag or AbortController? Use the flag when you cannot cancel the work (a third-party function that returns a promise). Use the controller when the API supports signals, so the browser stops downloading. Many projects do both. Either way, once you add loading, error and retry states plus caching to this effect, you are rebuilding a data library, which is why Fetching Data and Caching and Server State recommend a library or a framework for anything beyond simple cases. The related patterns (debounce, cancellation, retry) get their own lesson in Async Patterns and Race Conditions.

Cleanup recipes and mistakes

Resource Setup Cleanup
Interval const id = setInterval(...) clearInterval(id)
Timeout const id = setTimeout(...) clearTimeout(id)
DOM listener target.addEventListener(type, fn) target.removeEventListener(type, fn)
Observer observer.observe(node) observer.disconnect()
Connection const conn = connect() conn.close()
Request new AbortController() controller.abort()
Async result let ignore = false ignore = true

Common mistakes:

  • Cleanup that is not a mirror. Adding a listener inline (addEventListener('x', () => ...)) and then trying to remove a different inline function does nothing.
  • Reading state in the cleanup and expecting the latest value. The cleanup sees the values of the render that created the effect. Use a ref (see useRef) if you truly need the latest.
  • Returning a promise. useEffect(async () => ...) returns a promise, not a cleanup function, and React complains. Define an inner async function and call it, as in the fetching examples (.then chains work equally well).
  • Resetting with a flag instead of fixing the cleanup to make StrictMode quiet.
  • Forgetting that unrelated state changes re-run effects whose dependencies include unstable objects, creating and destroying timers or connections far too often.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does React run an effect's cleanup function?

    Cleanup runs before the next run of the same effect (with the old values) and on unmount. That is what keeps each setup and cleanup cycle self-contained.
  2. 2. Under StrictMode in development, what do you see in the console when a component with a connect/disconnect effect first mounts?

    React runs setup, cleanup and setup again to check that the cleanup reverses the setup. The final state is one open connection.
  3. 3. Why does window.removeEventListener('resize', () => setWidth(window.innerWidth)) not remove the listener?

    Removal compares function references (and capture option). Keep the handler in a named constant and pass that same constant to both calls.
  4. 4. A search effect fires a request for each keystroke and sometimes shows results for an old term. What is the standard fix?

    The cleanup of the previous run executes before the next one starts, so it can abort the request or mark its closure as stale. A late answer can then no longer overwrite newer data.
  5. 5. What is wrong with useEffect(async () => { ... })?

    React expects the effect to return nothing or a cleanup function. Declare an async function inside the effect and call it, or use promise chains.

Summary

  • A cleanup function is returned from the effect; React runs it before the next run of that effect and on unmount.
  • Cleanup must mirror setup: clear the timer id you got, remove the same listener function, close the connection you opened.
  • In development, StrictMode runs setup, cleanup, setup on mount to expose cleanups that do not fully reverse the setup. Fix the cleanup rather than silencing the double run.
  • Async work needs cleanup too: set an ignore flag or abort with AbortController so a stale response cannot overwrite newer state, and treat AbortError as normal.
  • The cleanup sees the values of the render that created it, which is why each cycle disconnects the right resource.
  • For anything beyond simple fetching, prefer a data library or framework rather than hand-written effects.

Next: You Might Not Need an Effect