Skip to content
Back to all posts
Technologymemory leaks in React applications

Memory Leaks in React: Causes, Cleanup, and Debugging

Find retained timers, listeners, subscriptions, and DOM references in React apps, then clean them up with effect lifecycles and browser memory tools.

4 min readUpdated June 27, 2026AI-assisted

TechSilo

AI-assisted and human-curated

A React component disappearing from the screen does not guarantee that every resource it started has stopped. An interval can keep firing, a WebSocket can remain open, and a global event listener can retain a callback that closes over component data.

Those are the kinds of references that can keep objects alive longer than intended. The fix is not to memoize every component; it is to identify what remains reachable and clean up the resource that owns it.

What a React memory leak looks like

Common symptoms include memory usage that grows after repeatedly opening and closing a screen, detached DOM nodes accumulating in a heap snapshot, duplicate event handlers, and background requests continuing after navigation.

A state update after unmount is not, by itself, proof of a memory leak. React 18 removed the old warning about state updates on unmounted components because it often flagged harmless cases. Look for retained resources and repeatable memory growth instead.

Clean up timers and subscriptions

An effect that starts an interval should return a cleanup function that stops that interval. Use the functional state updater so the callback does not need to capture a changing count value.

tsx
'use client';

import { useEffect, useState } from 'react';

export function Clock() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const timerId = window.setInterval(() => {
      setSeconds((current) => current + 1);
    }, 1000);

    return () => {
      window.clearInterval(timerId);
    };
  }, []);

  return <p>Elapsed: {seconds}s</p>;
}

The empty dependency array means this effect is set up when the component mounts and cleaned up when it unmounts. If dependencies change, React runs the previous cleanup before starting the effect again. The cleanup must mirror the resource created by the setup.

Apply the same rule to event listeners:

tsx
useEffect(() => {
  function handleResize() {
    console.log(window.innerWidth);
  }

  window.addEventListener('resize', handleResize);
  return () => window.removeEventListener('resize', handleResize);
}, []);

For WebSockets, observers, subscriptions, and third-party widgets, call the matching close(), disconnect(), unsubscribe(), or disposal method.

Cancel requests that no longer matter

A request started by a screen may finish after the user navigates away. An AbortController lets the effect cancel its fetch when it is cleaned up.

tsx
import { useEffect, useState } from 'react';

type Profile = { name: string };

export function ProfilePanel() {
  const [profile, setProfile] = useState<Profile | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const controller = new AbortController();

    async function loadProfile() {
      try {
        const response = await fetch('/api/profile', {
          signal: controller.signal,
        });

        if (!response.ok) {
          throw new Error(`Request failed: ${response.status}`);
        }

        const result = (await response.json()) as Profile;
        setProfile(result);
      } catch (err) {
        if (err instanceof Error && err.name === 'AbortError') return;
        setError(err instanceof Error ? err.message : 'Unknown error');
      }
    }

    void loadProfile();
    return () => controller.abort();
  }, []);

  if (error) return <p role="alert">{error}</p>;
  if (!profile) return <p>Loading profile…</p>;
  return <p>{profile.name}</p>;
}

For data-heavy applications, prefer the framework's data-loading facilities or a query library when they provide caching, deduplication, and request lifecycle management. Do not add a library just to hide a missing cleanup function.

Find the retained object

When memory keeps growing, reproduce the same navigation or interaction several times and inspect the browser's Memory panel:

1. Take a heap snapshot before the repeated action.

2. Open and close the relevant route or component several times.

3. Force garbage collection in the DevTools panel when available, then take another snapshot.

4. Compare snapshots and inspect objects with increasing retained size.

5. Follow the retaining path to see which listener, timer, cache, or global reference keeps the object alive.

A detached DOM node can indicate that JavaScript still references a node removed from the document. The React DevTools Profiler is useful for render behavior, but it is not a replacement for heap snapshots when diagnosing retained memory.

Mistakes that do not fix a leak

- Adding memo everywhere: React's built-in memo can skip some renders; it does not release an interval or close a socket.

- Using weak references as a blanket fix: weak references are specialized tools, not a substitute for a clear ownership and cleanup model.

- Suppressing warnings: hiding a message does not release retained objects.

- Adding dependencies blindly: a query or state library may improve data lifecycle management, but it cannot fix arbitrary listeners and timers created elsewhere.

React's [effect documentation](https://react.dev/reference/react/useEffect) describes setup and cleanup behavior, including the extra development-only setup/cleanup cycle in Strict Mode. Make each effect safe to start, stop, and start again. That discipline prevents many resource leaks before you need a heap profiler.

Want to put this into practice?

Explore TechSilo's free developer tools for practical utilities you can use directly in your browser.

Related blog posts