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

推荐订阅源

P
Privacy International News Feed
爱范儿
爱范儿
H
Help Net Security
博客园 - 三生石上(FineUI控件)
Engineering at Meta
Engineering at Meta
WordPress大学
WordPress大学
博客园 - 叶小钗
Google DeepMind News
Google DeepMind News
GbyAI
GbyAI
T
Tenable Blog
Project Zero
Project Zero
腾讯CDC
Spread Privacy
Spread Privacy
V
Vulnerabilities – Threatpost
T
Threatpost
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Latest news
Latest news
L
Lohrmann on Cybersecurity
B
Blog RSS Feed
小众软件
小众软件
G
Google Developers Blog
T
Tor Project blog
P
Palo Alto Networks Blog
The Cloudflare Blog
Scott Helme
Scott Helme
D
Darknet – Hacking Tools, Hacker News & Cyber Security
A
Arctic Wolf
博客园 - 聂微东
AWS News Blog
AWS News Blog
L
LINUX DO - 热门话题
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
D
Docker
博客园 - Franky
Know Your Adversary
Know Your Adversary
人人都是产品经理
人人都是产品经理
博客园 - 【当耐特】
P
Privacy & Cybersecurity Law Blog
A
About on SuperTechFans
Cisco Talos Blog
Cisco Talos Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
量子位
C
Cisco Blogs
P
Proofpoint News Feed
雷峰网
雷峰网
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
B
Blog
Security Latest
Security Latest
C
Cybersecurity and Infrastructure Security Agency CISA
Jina AI
Jina AI
Y
Y Combinator Blog

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
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