Skip to main content

One post tagged with "React"

View All Tags

React Memory Leaks: useEffect Cleanup Mistakes That Only Show Up in Production

Published: · 10 min read
Sandra Rosa Antony
Software Engineer, Appxiom

A missing useEffect cleanup rarely breaks anything on your laptop. You open the page, click around for a minute, and hot reload wipes the slate every time you save a file. Your users work differently. They keep a dashboard tab open all day, move between routes dozens of times, and never reload. Every effect that subscribes to something and forgets to let go adds a little more to the heap, until the tab gets slow, the fan spins up, or the browser kills the page. This post walks through the cleanup mistakes that cause most React memory leaks, how to fix each one, and how to confirm a leak in production instead of guessing.

Prerequisites​

The examples in this post run as written with:

  • React 18 or React 19, using function components and hooks.
  • Any current version of Chrome or Edge for the DevTools Memory panel steps. Firefox and Safari have equivalent heap tools with different menus.
  • Node.js 18 or later to build the app.
  • The Appxiom React SDK (npm install @appxiom/4react react) if you want leak signals from real user sessions. Setup steps are in the React SDK installation guide.

How useEffect cleanup works​

An effect can return a function, and React calls that function before the effect runs again and when the component unmounts. That returned function is the cleanup. Its job is to undo whatever the effect set up: remove a listener, clear a timer, close a socket, cancel a request.

useEffect(() => {
// setup
const id = setInterval(tick, 1000);

// cleanup
return () => clearInterval(id);
}, []);

If the effect sets something up and returns nothing, the thing it created outlives the component. The component is gone from the screen, but a timer, a listener or a subscription still holds a reference to its closure. Anything that closure captures, including props, state, DOM nodes and large arrays, cannot be garbage collected.

Why the leak hides in development​

Three things keep these leaks out of sight while you build.

In developmentIn production
Hot reload and frequent full reloads reset the heapA single-page app can run for hours without a reload
You visit a route a few timesUsers switch routes and open modals hundreds of times
Small test dataReal lists, images and API payloads that make each leaked closure heavier
A fast laptop with plenty of memoryOlder phones and low-memory laptops where the browser discards the tab

React 18 added one safety net. In Strict Mode during development, React mounts each component, runs its effects, unmounts it and mounts it again. A missing cleanup often shows up as a doubled listener or a second interval. That check only runs in development and only on components wrapped in <StrictMode>, so it catches some mistakes and says nothing about how the app behaves after two hours in a user's browser.

React 18 also removed the old "Can't perform a React state update on an unmounted component" warning. The warning was noisy and often wrong, but it was the one hint many teams relied on. Without it, a stale async callback runs quietly.

Five useEffect cleanup mistakes and their fixes​

These are the patterns that account for most React memory leaks in long-lived pages.

1. Event listeners on window or document​

A component adds a listener to a global object and never removes it.

// Leaks: every mount adds another listener
useEffect(() => {
window.addEventListener('resize', handleResize);
}, []);
// Fixed
useEffect(() => {
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);

removeEventListener only works when it receives the same function reference that was added. If you define the handler inline inside the effect, keep it in a variable so the cleanup can pass it back. An AbortController signal is a tidy alternative when one effect adds several listeners:

useEffect(() => {
const controller = new AbortController();
window.addEventListener('resize', handleResize, { signal: controller.signal });
document.addEventListener('keydown', handleKey, { signal: controller.signal });
return () => controller.abort();
}, []);

2. Intervals and timeouts​

setInterval keeps calling its callback until you clear it, and the callback keeps its closure alive.

// Fixed
useEffect(() => {
const id = setInterval(() => {
setNow(Date.now());
}, 1000);
return () => clearInterval(id);
}, []);

A setTimeout with a long delay, such as a retry after 30 seconds, needs the same treatment with clearTimeout. Polling loops built from chained timeouts are easy to miss because each call schedules the next one.

3. Subscriptions, sockets and observers​

WebSockets, EventSource, store subscriptions, ResizeObserver, IntersectionObserver and MutationObserver all hold callbacks until you close or disconnect them.

useEffect(() => {
const socket = new WebSocket(url);
socket.addEventListener('message', onMessage);

const observer = new ResizeObserver(onResize);
observer.observe(containerRef.current);

return () => {
socket.close();
observer.disconnect();
};
}, [url]);

Note the dependency array. When url changes, React runs the cleanup for the old socket before the setup for the new one. Without the cleanup, every URL change leaves a live connection behind.

4. Async requests that finish after unmount​

A fetch that resolves after the component has unmounted still runs its .then, still parses the response and still holds the closure until it settles. On a slow network, a user who clicks through a list quickly can leave a dozen of these in flight. Cancel them with AbortController:

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

fetch(`/api/orders/${orderId}`, { signal: controller.signal })
.then((res) => res.json())
.then(setOrder)
.catch((err) => {
if (err.name !== 'AbortError') setError(err);
});

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

The AbortError check matters. Aborting rejects the promise, and without a .catch you trade a leak for an unhandled rejection. Our post on unhandled promise rejections in JavaScript covers why those slip past try/catch and window.onerror.

5. Refs and module-level caches that keep growing​

useRef survives re-renders, which makes it a convenient place to stash data. It becomes a leak when the ref holds something large that is also registered somewhere global, or when a module-level Map or array collects an entry per component and nothing removes it.

const listeners = new Map(); // module scope, lives for the whole session

function LiveChart({ id }) {
const pointsRef = useRef([]);

useEffect(() => {
listeners.set(id, (point) => pointsRef.current.push(point));
return () => listeners.delete(id); // without this, every chart ever mounted stays reachable
}, [id]);

// ...
}

Two fixes apply here. Delete the entry in cleanup, and cap what the ref accumulates, for example by keeping only the last 500 points. Detached DOM nodes follow the same pattern: a ref or cache that still points at an element React has removed keeps the whole subtree in memory.

How to confirm a React memory leak in DevTools​

Before changing code, reproduce the leak and measure it. Chrome's Memory panel is enough for most cases.

  1. Open the page in an incognito window so extensions do not add noise, then open DevTools and go to the Memory panel.
  2. Take a heap snapshot as a baseline.
  3. Repeat the suspect interaction 10 to 20 times: open and close the modal, or navigate to the route and back.
  4. Click the trash icon to force garbage collection, then take a second snapshot.
  5. Switch the second snapshot to Comparison view against the first. Sort by # Delta or Size Delta and look for counts that grew in step with your repetitions, such as listeners, closures named after your handlers, or Detached DOM elements.
  6. Select a retained object and read its Retainers list. It shows the chain that keeps the object alive, which usually ends at the listener, timer or cache you forgot to clean up.

If heap size goes up after each round and does not come back down after garbage collection, you have a leak. If it climbs and then levels off, you are probably looking at caching that is working as designed.

Catching useEffect cleanup leaks in production​

DevTools tells you about the interaction you thought to test. Production leaks come from the sequence you did not think of: a filter panel opened 40 times, a route a support agent reopens all shift, a component that only mounts for one customer's account type. To find those, you need signals from real sessions.

The Appxiom React SDK (@appxiom/4react) adds this without component-level wrappers. After you call init before rendering, it records lifecycle activity for useEffect, useLayoutEffect, useState, useReducer, useMemo and useCallback, and it tracks useRef instances for leak analysis. Memory problems are reported as structured issue types, MemoryLeak, MemorySpike, MemoryAnomaly and MemoryRisk, so a leak shows up as an issue with the activity that led to it instead of a vague complaint that "the app gets slow."

import init from '@appxiom/4react';
import { createRoot } from 'react-dom/client';
import App from './App';

const ax = await init(
'YOUR_APP_KEY',
'YOUR_PLATFORM_KEY',
'YOUR_APP_VERSION',
'YOUR_BUILD_IDENTIFIER',
);

createRoot(document.getElementById('root')).render(<App />);

For server-rendered frameworks such as Next.js, load and initialize the SDK only in client code. The React SDK integration guide shows the client-only pattern and the Vite settings the SDK needs.

If you work with an AI coding agent, connect it to the Appxiom MCP server and ask it something like "List the memory issues reported in the latest release and the components involved." The agent reads the issue and its occurrence telemetry, then opens the matching effect in your codebase so you can review the missing cleanup in place. The same approach is shown for mobile in how Appxiom MCP helps iOS developers debug and fix bugs faster.

Decide which leak to fix first​

A leak on a settings page that users visit once a month can wait. A leak on the screen where users build a cart or file a ticket cannot, because the slowdown lands in the middle of the journey that pays for the app. Appxiom's Goal Friction Impact ties issues to the goals you mark with ax.startGoal and ax.endGoal, so you can see which leaks sit on a revenue path. The thinking behind that is in our post on measuring the revenue cost of broken user journeys.

Memory leaks are not unique to the web. If your team also ships mobile apps, the same mindset applies to memory leaks in Jetpack Compose and memory leaks in Flutter.

A cleanup checklist for code review​

Use this when you review any effect:

  • Does the effect create anything that outlives a render: a listener, timer, socket, observer, subscription or request?
  • Does it return a cleanup that undoes each of those?
  • Does the cleanup receive the same references the setup used?
  • When a dependency changes, does the old resource get released before the new one starts?
  • Do refs and module-level collections have a size limit or a removal path?

Every effect that sets something up should tear it down. Get that rule into code review, confirm suspected leaks with heap snapshots, and watch real sessions so the leaks your tests never trigger still reach you. To start collecting React leak signals from production, follow the React SDK integration guide.