Your app runs fine for ten minutes. Then the scroll gets sticky. After half an hour the tab hits a gigabyte. Eventually the page dies with an out-of-memory error and you have no stack trace to show for it.

This is not a render performance problem. The React DevTools Profiler will look quiet because the issue is not how often components redraw. The issue is what stays alive after they unmount. A stray reference somewhere in the JavaScript heap pins an entire tree of DOM nodes, closures, and state. The browser cannot reclaim any of it, so memory climbs until the process collapses.

Reading your source code will not reveal the leak. The bug lives in the gap between what you think unmounted and what the garbage collector actually sees. V8 only frees objects that have zero retaining paths. If a rogue event listener, an uncleared observer, or a long-lived closure holds even one pointer to a fiber or a DOM node, the whole component subtree survives. You unmount a modal, but its detached nodes remain in memory because a listener on window still points to a handler defined inside that modal.

To prove where the leak lives you need to look at the heap, not the editor.

Why the Heap Tells the Truth

Chrome DevTools gives you a direct window into what the garbage collector sees. The Memory tab can record heap snapshots: complete inventories of every object, DOM node, and closure currently held in JavaScript memory. By comparing two snapshots—one before a suspected leak and one after—you can isolate exactly which objects failed to die.

This is not abstract theory. A single leaked React component can retain thousands of detached HTMLElement objects. Those objects are no longer attached to the visible document, but JavaScript references prevent them from being collected. They show up in the comparison view with the constructor name Detached HTMLElement. When you see them multiplying, you have found your leak.

The Chrome DevTools Workflow

Start clean. Close unrelated browser tabs, disable unrelated extensions, and let your application settle into a steady state. Open Chrome DevTools, switch to the Memory tab, and select Heap snapshot. Click Take snapshot. This baseline captures your starting memory footprint.

Now perform the exact user action you suspect. Open and close that heavy modal. Mount and unmount the widget. Navigate to the route and back. Once the UI has returned to its original visual state, click the trash can icon in the Memory tab. This forces a global garbage collection pass. Temporary objects from the render cycle should drop away. Anything that remains is a real candidate for a leak.

Click Take snapshot again. You now have two photographs of memory. Change the view from Summary to Comparison. Set the comparison scope to the first snapshot. The tool will show you only what changed between the two captures, stripping away the noise of the runtime.

Sort by Delta. Look for object counts that grew. Pay special attention to constructors like Detached HTMLElement, Array, Function, or even named class instances from your own codebase. A rising delta means objects were created during your action and were not collected afterward.

Tracing the Retaining Path

When you spot a leaked element, select it. The bottom panel displays the retaining path: a chain of references that explains why this object is still alive. The chain might run from a detached div up through React internal properties, into a closure, and finally land on an event listener registered inside one of your components. That final link in the chain is your line number.

This is where you move from diagnosis to root cause. If the retaining path ends at window.addEventListener, you know a global listener is holding your component hostage. If it ends at an IntersectionObserver instance, you know an observer is still watching a node that should have been garbage collected.

Common Culprits in React

Memory leaks in React usually fall into three patterns.

Orphaned global listeners. A useEffect hooks into window or document to track scroll position, key presses, or resize events. If the effect does not return a cleanup function that calls removeEventListener, the listener survives for the lifetime of the page. Because the listener is a closure, it keeps the entire component scope alive long after React has unmounted the component.

Observer non rimossi. IntersectionObserver e ResizeObserver sono potenti, ma creano riferimenti nativi al di fuori del controllo di React. Se istanzi un observer all'interno di un componente e dimentichi di chiamare disconnect() nella fase di cleanup, l'observer manterrà il nodo DOM di destinazione, e il nodo DOM manterrà i React fiber, le props e lo stato.

Trappole delle closure. Quando definisci una funzione all'interno di un componente e la passi a una libreria di terze parti, a una cache globale o persino a setTimeout, quella funzione crea una closure su ogni variabile nel suo scope lessicale. Se il proprietario esterno mantiene la funzione in memoria, manterrà con sé l'intero scope del componente.

Pattern di cleanup che funzionano davvero

Risolvere un leak significa interrompere ogni percorso di ritenzione (retaining path) individuato nello snapshot.

Restituisci sempre una funzione di cleanup da useEffect. Se aggiungi un listener nell'effect, rimuovilo lì.

Usa useCallback per qualsiasi handler che attacchi al DOM o a window. Senza di esso, ogni render crea un nuovo riferimento alla funzione. Se chiami addEventListener con un riferimento e successivamente chiami removeEventListener con uno diverso, la rimozione fallirà silenziosamente. Il listener originale rimarrà su window per sempre. useCallback mantiene il riferimento stabile in modo che add e remove corrispondano esattamente.

Gestisci gli observer con la stessa disciplina. Memorizza l'istanza dell'observer in una ref o in una variabile locale all'interno dell'effect. Nella funzione di cleanup, chiama observer.disconnect(). Non dare per scontato che l'unmount del componente interrompa l'observer. Non è così.

Se il tuo componente pubblica qualcosa in un namespace globale o in un servizio singleton, elimina quei riferimenti al momento dell'unmount. Il motore V8 può recuperare memoria solo quando un oggetto è realmente irraggiungibile. Lasciare un hook su window o una voce in una Map a livello di modulo crea un ponte invisibile che continua a far crescere l'heap.

Il punto fondamentale

I memory leak non mandano in crash l'app immediatamente. Si accumulano un nodo distaccato alla volta durante lunghe sessioni utente. La soluzione non è l'aggiornamento di una libreria o un flag del compilatore. È l'abitudine di verificare la propria logica di cleanup tramite heap snapshot.

Crea un baseline, attiva il flusso sospetto, forza il garbage collection e confronta i risultati. Se il delta mostra una crescita, ispeziona il retaining path, trova il listener o l'observer che non dovrebbe esistere e interrompi il riferimento. Esegui nuovamente il test. Quando il delta rimane costante, significa che hai risolto il problema. La tua applicazione rimarrà reattiva e i tuoi utenti non perderanno il loro lavoro a causa di una scheda del browser bloccata.