ReactMedium

What are memory leaks?

A memory leak in a React app is memory that stays allocated after it is no longer needed, usually because something outside React still references a component's closures or DOM nodes: event listeners, timers, subscriptions, observers, sockets or third-party widgets that were never cleaned up, or caches that grow without limit. Over time the app gets slower and can crash, especially in long-lived single-page apps.

Common sources

  • window/document listeners added in effects without removeEventListener.
  • setInterval/setTimeout not cleared.
  • WebSockets, EventSource, Firebase or store subscriptions not closed.
  • IntersectionObserver, ResizeObserver, MutationObserver not disconnected.
  • Third-party libraries (maps, charts, editors) not destroyed.
  • Unbounded caches or arrays in module scope, such as storing every message forever.
  • Detached DOM nodes held in refs or closures by long-lived objects.
  • Global event buses where handlers are registered on every mount.

Prevention

  • Return a cleanup from every effect that subscribes or schedules work.
  • Use ref callback cleanups (React 19) for observers attached to DOM nodes.
  • Cap caches (LRU), use WeakMap/WeakRef for metadata keyed by objects.
  • Let data libraries manage caching with garbage collection (gcTime in TanStack Query).
  • Test with Strict Mode: double mount and unmount reveals missing cleanups.

Finding leaks

Chrome DevTools Memory panel: take heap snapshots before and after repeating an action (open and close a modal ten times), compare retained objects, and look for "Detached" DOM nodes and growing listener counts. The Performance monitor shows JS heap size and listener counts over time.

Code example

tsx
1import { useEffect, useRef, useState } from "react";
2
3export function LivePrices({ symbols }: { symbols: string[] }) {
4 const [prices, setPrices] = useState<Record<string, number>>({});
5 const chartRef = useRef<{ destroy(): void } | null>(null);
6
7 useEffect(() => {
8 const ws = new WebSocket("wss://prices.example.com");
9 ws.onopen = () => ws.send(JSON.stringify({ subscribe: symbols }));
10 ws.onmessage = (e) => {
11 const { symbol, price } = JSON.parse(e.data);
12 setPrices((p) => ({ ...p, [symbol]: price }));
13 };
14
15 const onVisibility = () => document.hidden ? ws.send('{"pause":true}') : ws.send('{"pause":false}');
16 document.addEventListener("visibilitychange", onVisibility);
17
18 const id = setInterval(() => ws.readyState === WebSocket.OPEN && ws.send('{"ping":1}'), 30_000);
19
20 return () => {
21 // Every resource created above is released here
22 ws.close();
23 document.removeEventListener("visibilitychange", onVisibility);
24 clearInterval(id);
25 chartRef.current?.destroy();
26 };
27 }, [symbols]);
28
29 // React 19: ref callback cleanup for observers
30 const observe = (node: HTMLDivElement) => {
31 const ro = new ResizeObserver(() => {});
32 ro.observe(node);
33 return () => ro.disconnect();
34 };
35
36 return <div ref={observe}>{Object.entries(prices).map(([s, p]) => <p key={s}>{s}: {p}</p>)}</div>;
37}

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.

Open in study app