Your user's browser tab freezes after thirty minutes. The UI stutters. Then the browser crashes with an out-of-memory error.
You review the component code line by line and see nothing wrong. That is the maddening part of memory leaks in React. The bug does not live in your JSX syntax or your hook logic. It lives in the gap between your component and the browser's garbage collector. A stray event listener or a long-lived closure stops the collector from reclaiming memory. You unmount a component, but a single lingering reference keeps the entire tree alive in the heap. You cannot find these leaks by just reading code. The problem stays hidden under the surface, invisible to the eye and silent in unit tests.
Why Leaks Hide in Plain Sight
JavaScript engines like V8 manage memory automatically. When no reference path exists from the root to an object, the engine marks that object as garbage and reclaims the space. This process works well until a hidden reference survives longer than you intended.
In React, the danger often appears at the boundary between components and the DOM. You might attach a resize listener to the window inside a modal, or subscribe to a WebSocket in a dashboard widget. When the user closes the modal or navigates away, the component unmounts. If the subscription survives, the engine sees a valid reference from the global window object down to your handler, and from your handler back into the component's closure. The component, its props, its state, and its entire subtree of DOM nodes stay pinned in memory. Over hundreds of interactions, these pinned objects accumulate. Memory usage climbs in a sawtooth pattern that never fully drops back down.
The Enterprise Dashboard Problem
This happens most in enterprise dashboards where users stay on one page for hours. Think of monitoring panels, analytics views, or ticketing systems. A user opens a detail modal, filters a large dataset, or switches tabs within a single-page app. Each individual interaction feels fine. Over time, though, orphaned nodes and detached listeners accumulate. The application slows not because of a single expensive render, but because the heap grows large enough to trigger frequent and expensive garbage collection pauses.
Stop guessing about your useEffect hooks. The only way to know if a leak exists is to measure the heap directly. Chrome DevTools gives you that visibility.
Hunting Leaks with Chrome DevTools
You need a reproducible sequence and a few minutes of focused attention. Open your application in Chrome, launch DevTools, and navigate to the Memory tab.
Record a baseline. Select Heap snapshot and click Take snapshot. This captures every object currently living in the JavaScript heap and shows you the starting memory. Do this after the page has settled into its initial idle state, not during initial load, so you measure only the growth caused by user actions.
Trigger the action. Perform the exact UI interaction you suspect causes the leak. Open and close a modal, toggle a complex chart, or change a route and navigate back. Once finished, return the app to its original visual state. This step is crucial. You want the UI to look identical to how it looked during the baseline. If the heap has grown despite the UI appearing empty, you have strong evidence of a leak.
Force garbage collection. Click the trash can icon in the Memory tab. This triggers a full GC cycle and clears temporary objects that legitimately survived until the next collection. What remains are the real leaks, objects that should have been collected but were held alive by accidental references.
Take a second snapshot. Click Take snapshot again. You now have two photographs of the heap taken under the same UI conditions.
Compare results. Change the view from Summary to Comparison. Set the baseline to your first snapshot and the compared snapshot to the second. The Comparison view lists every object category and shows you the delta, the net change in object counts between the two captures.
Sort by Delta. Look for categories that increased significantly. Focus especially on Detached HTMLElement and React fiber nodes. A detached HTML element is a DOM node that is no longer attached to the active document tree, yet some JavaScript reference still holds it. These are smoking guns. They should not exist after you have closed a modal or unmounted a component.
Reading the Retaining Path
Коли ви вибираєте від'єднаний елемент у знімку (snapshot), Chrome показує шлях утримання (retaining path) у нижній панелі. Цей шлях — це ланцюжок посилань від кореня до вибраного об'єкта. Слідкуйте за ним уважно. Ви часто будете знаходити слухач подій (event listener), IntersectionObserver, ID setInterval або замикання (closure), що вказує на конкретний рядок у вашому компоненті.
Шукайте знайомі назви. Якщо ви бачите слухач, прикріплений до window, з назвою функції з вашого коду, ви знайшли «якір». Об'єкт, що утримує цей слухач, підтримує життя всього вашого компонента. Іноді ланцюжок проходить через сторонню бібліотеку. У таких випадках перевірте, чи не очікує бібліотека явного виклику методу завершення роботи (teardown), який ви забули викликати у функції очищення (cleanup function).
Усунення першопричин
Щойно ви визначите шлях утримання, виправлення зазвичай є механічним, але воно потребує дисципліни від усієї команди.
Використовуйте функції очищення. Завжди повертайте функцію очищення в useEffect, коли додаєте слухачів до window або document. Якщо ваш ефект підписується на подію зміни розміру (resize), видаліть це підписку перед розмонтуванням (unmount) компонента. Очищення виконується, коли React видаляє компонент, що дає вам гарантований механізм для розриву зовнішніх зв'язків.
Стабілізуйте посилання. Огортайте ваші обробники в useCallback. Це гарантує, що ви передасте в removeEventListener саме те посилання на функцію, яке спочатку передали в addEventListener. Якщо ви реєструєте інлайнову функцію, наприклад window.addEventListener('resize', () => { ... }), а потім намагаєтеся видалити її за допомогою іншої інлайнової функції, посилання не співпадуть. Слухач залишиться прикріпленим. Замикання всередині нього підтримуватиме стан вашого компонента живим. useCallback зі стабільним масивом залежностей запобігає цій невідповідності ідентичності.
Розривайте глобальні зв'язки. Пам'ятайте, що об'єкти цілей подій браузера, такі як window та document, існують протягом усього часу життя сторінки. Будь-яке посилання від них на ваш компонент діє як глобальний якір. Видалення слухача розриває цей якір і дозволяє двигуну V8 видалити стан компонента та DOM-вузли під час наступного циклу збору сміття (garbage collection).
Розглянемо модальне вікно, яке відстежує ширину вікна. Без очищення щоразу, коли користувач відкриває модальне вікно, прикріплюється новий слухач. Старі ніколи не від'єднуються, тому що екземпляри компонентів, до яких вони належать, зникли, проте самі функції були анонімними та втраченими. Використання іменованого обробника, огортаного в useCallback, разом із функцією очищення, яка викликає removeEventListener, дозволяє чисто закрити цей цикл.
Практичний висновок
Витоки пам'яті в React рідко заявляють про себе чітким повідомленням про помилку. Вони заявляють про себе вкладкою, яка стає все важчою, чим довше вона відкрита. Не витрачайте час на здогади, який саме хук винен. Відкрийте вкладку Memory, примусово запустіть збір сміття (garbage collection) і порівняйте знімки (snapshots). Нехай профайлер купи (heap profiler) покаже вам точний шлях утримання. Потім напишіть функцію очищення, стабілізуйте посилання на callback і розірвіть глобальний зв'язок. Ваші користувачі не помітять виправлення безпосередньо, але вони помітять, що дашборд продовжує працювати плавно навіть наприкінці робочого дня.
