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/documentlisteners added in effects withoutremoveEventListener.setInterval/setTimeoutnot cleared.- WebSockets,
EventSource, Firebase or store subscriptions not closed. IntersectionObserver,ResizeObserver,MutationObservernot 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/WeakReffor metadata keyed by objects. - Let data libraries manage caching with garbage collection (
gcTimein 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
1import { useEffect, useRef, useState } from "react";23export function LivePrices({ symbols }: { symbols: string[] }) {4 const [prices, setPrices] = useState<Record<string, number>>({});5 const chartRef = useRef<{ destroy(): void } | null>(null);67 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 };1415 const onVisibility = () => document.hidden ? ws.send('{"pause":true}') : ws.send('{"pause":false}');16 document.addEventListener("visibilitychange", onVisibility);1718 const id = setInterval(() => ws.readyState === WebSocket.OPEN && ws.send('{"ping":1}'), 30_000);1920 return () => {21 // Every resource created above is released here22 ws.close();23 document.removeEventListener("visibilitychange", onVisibility);24 clearInterval(id);25 chartRef.current?.destroy();26 };27 }, [symbols]);2829 // React 19: ref callback cleanup for observers30 const observe = (node: HTMLDivElement) => {31 const ro = new ResizeObserver(() => {});32 ro.observe(node);33 return () => ro.disconnect();34 };3536 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.