惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
小众软件
小众软件
博客园 - 叶小钗
宝玉的分享
宝玉的分享
博客园_首页
Hugging Face - Blog
Hugging Face - Blog
人人都是产品经理
人人都是产品经理
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
SegmentFault 最新的问题
B
Blog RSS Feed
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
Google DeepMind News
Google DeepMind News
U
Unit 42
F
Fortinet All Blogs
IT之家
IT之家
Y
Y Combinator Blog
Martin Fowler
Martin Fowler
T
The Blog of Author Tim Ferriss
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The GitHub Blog
The GitHub Blog
Stack Overflow Blog
Stack Overflow Blog
Blog — PlanetScale
Blog — PlanetScale
酷 壳 – CoolShell
酷 壳 – CoolShell

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
React Memory Leaks: Closures and Object Graphs
Ashish Kumar · 2026-05-04 · via DEV Community

Memory leaks in JavaScript don't announce themselves with an error. They show up as a heap that grows by 20MB per minute — invisible in a five-minute Lighthouse run, fatal in a six-hour production session.

Why React apps leak: A useEffect that opens a WebSocket and never closes it on unmount. A setInterval without clearInterval in the cleanup return. A global Map that grows without bound. In each case, something still holds a reference to objects that are no longer logically needed, and the GC cannot collect what it can still reach.

What this covers: The six React leak patterns found in production, how to use Chrome's heap snapshot diff to confirm a leak, the AbortController pattern for async cleanup, and when to use WeakMap and WeakRef.

Diagram of a retained object graph: GC roots through listeners and closures keeping React state and large data alive.


What a Memory Leak Actually Is

In JavaScript, the garbage collector (GC) automatically frees memory when objects are no longer reachable. A memory leak occurs when objects that are no longer logically needed are still reachable something in the code still holds a reference to them, preventing collection.

The key concept is the retained object graph. When you have a memory leak, there's a chain of references from a live root (a global variable, a DOM node, an active event listener) down to the leaked object. The GC follows this chain and decides the object is still in use. You can't fix a leak by just "stopping using" the object you have to break the reference chain.

GC Root → EventTarget → Event Listener → Handler Function → Closure → Component State → Large Data Structure

Enter fullscreen mode Exit fullscreen mode

Every node in that chain stays in memory as long as the chain exists. Removing your reference to the component doesn't matter if a global EventTarget still holds a reference to a handler that closes over that component's state.


The Six React Leak Patterns

1. Event Listeners Not Removed in useEffect Cleanup

This is the most common beginner mistake:

// Leaks: adds a new listener on every render, never removes any
function WindowSize() {
  const [size, setSize] = useState({ width: window.innerWidth });

  useEffect(() => {
    const handler = () => setSize({ width: window.innerWidth });
    window.addEventListener("resize", handler);
    // no cleanup: listener accumulates with every render
  });

  return <div>{size.width}px</div>;
}

Enter fullscreen mode Exit fullscreen mode

// Correct: cleanup removes the specific handler that was added
function WindowSize() {
  const [size, setSize] = useState({ width: window.innerWidth });

  useEffect(() => {
    const handler = () => setSize({ width: window.innerWidth });
    window.addEventListener("resize", handler);

    return () => window.removeEventListener("resize", handler);
  }, []); // empty dep array: runs once, cleanup runs on unmount

  return <div>{size.width}px</div>;
}

Enter fullscreen mode Exit fullscreen mode

The useEffect return function is the cleanup. React calls it before re-running the effect (if dependencies changed) and when the component unmounts. The handler variable must be the same reference passed to both addEventListener and removeEventListener a common mistake is creating a new arrow function in the cleanup, which doesn't match the one that was added.

2. setInterval / setTimeout Not Cleared

// Leaks: interval keeps running after component unmounts
function LiveClock() {
  const [time, setTime] = useState(new Date());

  useEffect(() => {
    const id = setInterval(() => setTime(new Date()), 1000);
    return () => clearInterval(id); // this is required
  }, []);

  return <div>{time.toLocaleTimeString()}</div>;
}

Enter fullscreen mode Exit fullscreen mode

Without clearInterval, the interval fires every second forever. Each invocation calls setTime, which holds a reference to the setTime function, which is part of the component's fiber, keeping the component's state and potentially any closed-over variables alive indefinitely. In development with React's StrictMode (which double-invokes effects), you'll see this immediately.

3. WebSocket / SSE Subscriptions That Outlive the Component

The leak we started with:

// Leaks: opens a new WebSocket on every mount, never closes it
function LiveFeed() {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const ws = new WebSocket("wss://api.example.com/feed");
    ws.onmessage = (event) => {
      setMessages((prev) => [...prev, JSON.parse(event.data)]);
    };
    // no ws.close()  connection and handler stay alive after unmount
  }, []);

  return ;
}

Enter fullscreen mode Exit fullscreen mode

// Correct
function LiveFeed() {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const ws = new WebSocket("wss://api.example.com/feed");
    ws.onmessage = (event) => {
      setMessages((prev) => [...prev, JSON.parse(event.data)]);
    };

    return () => ws.close();
  }, []);

  return ;
}

Enter fullscreen mode Exit fullscreen mode

For EventSource (SSE), the same pattern applies: return () => eventSource.close(). For libraries like Socket.io: return () => socket.disconnect().

4. Stale Closures in Event Handlers

This is subtler and doesn't always cause a leak in the traditional sense, but it causes handlers to retain old state indefinitely:

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const handler = () => {
      // This closure captures `count` at the time the effect ran
      // If count is 0 when this effect ran, it will always log 0
      console.log("current count:", count);
    };

    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, []); // BUG: `count` in deps array should be here

  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}

Enter fullscreen mode Exit fullscreen mode

The closed-over count value from the first render is captured in the handler and never updated. The handler holds a stale reference to the old state. Use a ref to get the current value without re-registering the listener:

function Counter() {
  const [count, setCount] = useState(0);
  const countRef = useRef(count);
  countRef.current = count; // always in sync

  useEffect(() => {
    const handler = () => console.log("current count:", countRef.current);
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, []); // countRef never changes, handler never needs re-registration

  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}

Enter fullscreen mode Exit fullscreen mode

5. Global Caches That Grow Unboundedly

Module-level Map and Set instances are GC roots. Anything stored in them is alive as long as the module is alive which in a long-running SPA is forever.

// In a module  this cache lives for the lifetime of the app
const responseCache = new Map();

async function fetchUser(id) {
  if (responseCache.has(id)) return responseCache.get(id);
  const data = await api.get(`/users/${id}`);
  responseCache.set(id, data); // never evicted
  return data;
}

Enter fullscreen mode Exit fullscreen mode

After visiting 10,000 user profiles (common in an internal admin tool), responseCache holds 10,000 entries. Add LRU eviction:


const responseCache = new LRUCache({ max: 100 }); // evicts oldest when full

Enter fullscreen mode Exit fullscreen mode

Or use WeakMap when the keys are objects entries are automatically evicted when the key object is garbage collected:

const nodeDataCache = new WeakMap(); // keys are DOM nodes or component instances
// When the DOM node is removed, its entry is automatically freed

Enter fullscreen mode Exit fullscreen mode

6. Third-Party Library Subscriptions Not Unsubscribed

Zustand, Redux, and RxJS all provide subscription mechanisms. Each one can leak if not cleaned up:

// Zustand: subscribe outside of React's lifecycle management
useEffect(() => {
  const unsubscribe = useStore.subscribe(
    (state) => state.theme,
    (theme) => applyTheme(theme)
  );
  return () => unsubscribe(); // required
}, []);

// RxJS observable subscription
useEffect(() => {
  const subscription = dataStream$.subscribe((data) => setData(data));
  return () => subscription.unsubscribe();
}, []);

Enter fullscreen mode Exit fullscreen mode

The pattern is always the same: capture the unsubscribe/unregister/dispose function from the subscription call, and return it from useEffect. If the library doesn't return a cleanup function, look for .off(), .removeListener(), or .destroy() methods.


Using Chrome DevTools to Find Leaks

The Heap Snapshot Diff Technique

The most reliable way to confirm a suspected leak:

  1. Open Chrome DevTools → Memory tab
  2. Take a Heap Snapshot (baseline)
  3. Perform the action you think causes a leak (navigate to a component and back, do it 5-10 times)
  4. Click the trash icon to force a garbage collection
  5. Take a second Heap Snapshot
  6. In the second snapshot, change the dropdown from "Summary" to "Comparison" and compare against the first snapshot

The "# Delta" column shows objects added vs freed. If you see the same constructor name appearing with a large positive delta after navigating away and back, that's your leak. Look for your component names, WebSocket, EventSource, or familiar data shapes.

Detached DOM nodes are a specific class of leak worth calling out. They appear in heap snapshots labeled as Detached HTMLDivElement or similar. These are DOM nodes that have been removed from the live document but are still referenced by JavaScript usually by an event handler or a variable that wasn't cleared. Filter by "Detached" in the heap snapshot class filter to find them.

Memory Timeline: Seeing the Leak in Real Time

For the kind of leak we started with gradual heap growth the Allocation Timeline is more useful than snapshots:

  1. DevTools → Memory → Allocation instrumentation on timeline
  2. Click record, use the app normally for 1-2 minutes
  3. Stop recording

The timeline shows a blue bar for each allocation. A healthy app shows allocations and corresponding GC: the heap drops back down). A leaking app shows a sawtooth that ratchets upward allocations outpace collections, and the heap baseline rises with each cycle.

You can click any time range in the timeline to see what was allocated during that period. If the leaking objects appear consistently during a specific interaction (switching routes, receiving WebSocket messages), you've found your reproduction path.


WeakMap and WeakRef for Caches

WeakMap keys must be objects and do not prevent garbage collection of the key. This makes them ideal for attaching metadata to objects without leaking:

const cache = new WeakMap();

function processElement(element) {
  if (cache.has(element)) return cache.get(element);
  const result = expensiveComputation(element);
  cache.set(element, result);
  return result;
}
// When `element` is removed from the DOM and has no other references,
// its WeakMap entry is automatically freed

Enter fullscreen mode Exit fullscreen mode

WeakRef (ES2021) lets you hold a weak reference to an object a reference that doesn't prevent GC. Use it for caches where you want to keep the cached value if it's still alive but don't need to keep it alive yourself:

class ComponentCache {
  #cache = new Map();

  set(key, value) {
    this.#cache.set(key, new WeakRef(value));
  }

  get(key) {
    const ref = this.#cache.get(key);
    if (!ref) return undefined;
    const value = ref.deref(); // returns undefined if GC'd
    if (!value) {
      this.#cache.delete(key); // clean up the dead entry
      return undefined;
    }
    return value;
  }
}

Enter fullscreen mode Exit fullscreen mode

WeakRef is a power-user API: don't reach for it as a default. The GC timing is non-deterministic and behavior can differ between environments. Use it when you genuinely want cache semantics where the backing store self-evicts.


The "Update State on Unmounted Component" Warning

React 17 and earlier would warn: Can't perform a React state update on an unmounted component. This was commonly interpreted as a memory leak indicator. It's actually more nuanced.

The warning fires when an async operation (a fetch, a setTimeout) completes after the component has unmounted and tries to call setState. React stops the update, but the warning correctly flags the pattern as a code smell: you're doing work that has no effect and potentially holding references longer than needed.

The AbortController pattern is the right fix for fetch-based async:

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

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

    async function load() {
      try {
        const res = await fetch(`/api/users/${userId}`, {
          signal: controller.signal,
        });
        const data = await res.json();
        setUser(data); // only runs if not aborted
      } catch (err) {
        if (err.name === "AbortError") return; // expected, not an error
        throw err;
      }
    }

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

  return user ? <div>{user.name}</div> : <div>Loading...</div>;
}

Enter fullscreen mode Exit fullscreen mode

When the component unmounts (or userId changes and the effect re-runs), controller.abort() cancels the in-flight request. The fetch throws an AbortError, which we catch and ignore. No state update fires after unmount: no warning, no dangling async work.

Note: React 18 removed this warning entirely because it was causing confusion: not all state updates on unmounted components are leaks, and the warning didn't distinguish between the cases. But the underlying pattern is still worth following.


A Diagnostic Checklist

When I suspect a memory leak in a React app, I work through this order:

Step Action
1 Open Chrome's Memory timeline, use the app for 2-3 minutes, check for ratcheting heap
2 Check all useEffect calls does every effect that adds a listener, starts an interval, or opens a connection have a cleanup return?
3 Audit module-level Maps and Sets do they have a max size or eviction strategy?
4 Take heap snapshots before and after repeating a suspected operation 10x, look for positive deltas
5 Filter heap snapshot by "Detached" to find orphaned DOM nodes
6 Check third-party subscriptions (Zustand, Redux, RxJS) for missing unsubscribe calls
7 If async ops fire after unmount, add AbortController or a mounted flag

Most leaks I've encountered in production React apps are caught by step 2. The cleanup return function in useEffect is the single most important habit for preventing leaks it's the React mechanism that gives you the opportunity to do the right thing, and forgetting it is the root cause of the majority of component-level leaks.


Read the original article on Renderlog.in:
https://renderlog.in/blog/react-memory-retained-graphs-leaks/

If you found this helpful, I've also built some free tools for developers and everyday users. Feel free to try them once:

JSON Tools: https://json.renderlog.in
Text Tools: https://text.renderlog.in
QR Tools: https://qr.renderlog.in