When does an object become a memory leak?
Garbage collection can reclaim objects that are no longer reachable. If a global collection, active timer or window listener still leads to an unnecessary object, it cannot be reclaimed. A reference cycle alone is not a leak if the entire cycle is unreachable. [1]
Distinguish a leak from intentional caching, temporary growth during data processing and allocation churn that increases GC frequency. Process memory includes more than the JavaScript heap; reclaiming an object does not necessarily reduce reported process memory immediately. [2]
Event listeners and detached DOM
resources.ts
export function subscribe(
target: EventTarget,
eventName: string,
listener: EventListener,
): () => void {
const controller = new AbortController();
target.addEventListener(eventName, listener, {
signal: controller.signal,
});
return () => controller.abort();
}Related article: JavaScript Event Bubbling, Capturing and Delegation
Suppose a panel registers a resize handler on window, and the function captures the panel. Removing the panel from the document does not remove the window listener. The path window → listener → panel may retain its subtree. A listener on an otherwise unreachable element does not automatically cause a leak. [1][2]
The subscribe function returns a cleanup procedure; call it on unmount and do not store it indefinitely. AbortController removes listeners tied to its signal. With manual removeEventListener, event type, callback and capture flag must match. A fresh mount needs a fresh controller. [3]
Timers, observers and other resources
resources.ts
export function observeSize(
element: Element,
onResize: ResizeObserverCallback,
): () => void {
const observer = new ResizeObserver(onResize);
observer.observe(element);
return () => observer.disconnect();
}Related article: IntersectionObserver vs ResizeObserver vs MutationObserver
For every setup identify the owner and matching cleanup: setInterval/clearInterval, setTimeout/clearTimeout, requestAnimationFrame/cancelAnimationFrame and ResizeObserver/disconnect. If a loop schedules another frame, stop rescheduling as well. A shared observer may need unobserve instead of disconnecting all targets. [12]
The observeSize function creates an observer for one element. Also release WebSocket connections (close), owned workers (terminate) and blob object URLs (revokeObjectURL, only after use ends). Do not close a shared resource that the component does not own. [4][5][6]
Asynchronous requests and stale results
request.ts
export async function loadText(
url: URL,
signal: AbortSignal,
): Promise<string> {
signal.throwIfAborted();
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const text = await response.text();
signal.throwIfAborted();
return text;
}
An in-flight request can retain callbacks and intermediate data. Abort fetch through AbortController when the result is no longer needed. In loadText the caller owns the signal; the function checks the HTTP status and cancellation state after reading the response. The owner must handle promise rejection and call abort on unmount. [7]
Cancellation cannot undo work already performed by the server. If an old operation can complete after a newer one, also check the current request identity before committing results. A data race is not itself a memory leak; diagnose both separately.
Bounded caches, Map and WeakMap
cache.ts
export class BoundedCache<V> {
private readonly entries = new Map<string, V>();
constructor(private readonly capacity: number) {
if (!Number.isSafeInteger(capacity)) {
throw new RangeError("Capacity must be a safe integer.");
}
if (capacity < 1) {
throw new RangeError("Capacity must be positive.");
}
}
get size(): number {
return this.entries.size;
}
get(key: string): V | undefined {
return this.entries.get(key);
}
set(key: string, value: V): void {
this.entries.delete(key);
this.entries.set(key, value);
if (this.entries.size <= this.capacity) {
return;
}
const oldest = this.entries.keys().next();
if (!oldest.done) {
this.entries.delete(oldest.value);
}
}
clear(): void {
this.entries.clear();
}
}
A global Map that grows with each query may retain unnecessary data for the whole session. BoundedCache limits entry count, evicts the least recently written key and refreshes write order on overwrite. Reads do not change order, so this is not LRU. An entry limit is not a byte limit; large values may need a weighted budget or TTL.
WeakMap associates metadata with an object without extending the key's lifetime. It cannot enumerate entries and does not replace a string-keyed cache policy. WeakRef and FinalizationRegistry do not guarantee cleanup timing; do not depend on them for essential resource disposal. [1][8][9]
React component lifecycle
use-window-resize.ts
import { useEffect } from "react";
import { subscribe } from "./resources";
export function useWindowResize(onResize: EventListener): void {
useEffect(() => {
return subscribe(window, "resize", onResize);
}, [onResize]);
}Related article: React useEffect: Dependencies, Cleanup and Common Mistakes
An Effect should release exactly the resource it created. useWindowResize returns subscribe's cleanup, so the old subscription is removed when onResize changes. If the callback gets a new identity each render, the Effect reruns; do not hide dependencies as a supposed optimization. [10]
In development Strict Mode can run an additional setup-cleanup-setup cycle. This tests cleanup symmetry, not proof of a leak. The example runs in a client Effect rather than accessing window during server rendering. [10]
How to diagnose a leak in Chrome DevTools
retention-lab.ts
export function createRetentionLab(host: HTMLElement) {
const retainedPanels = new Set<HTMLElement>();
function runCycle(retain: boolean): void {
const panel = document.createElement("section");
const title = document.createElement("h2");
title.textContent = "Temporary panel";
panel.append(title);
host.append(panel);
panel.remove();
if (retain) {
retainedPanels.add(panel);
}
}
function reset(): void {
retainedPanels.clear();
}
return { runCycle, reset };
}
Reproduce the problem in a fresh tab with comparable input. Open Memory, warm up, and take a baseline heap snapshot. Repeat, for example, 20 open-close cycles of the panel, return to the same state and take another snapshot; repeat the batch. If you use the DevTools GC button, follow the same procedure before every snapshot. [2][11]
Compare instance counts and sizes. Shallow size is the object's own size; retained size estimates memory that could be released if the object became unreachable, including objects retained exclusively through it. Inspect Retainers for a path to a GC root; Detached elements helps locate detached nodes. Avoid storing inspected objects in the console, which can itself retain them. [11]
Allocation instrumentation on timeline can reveal where objects surviving the measured interval were allocated, but allocation alone is not evidence of a leak. Remove the retaining cause and repeat the same scenario. Look for stabilization after warm-up, not identical byte counts in every sample. [2]
To practise diagnosis, create lab with createRetentionLab(document.body) in a browser module and keep the instance for the experiment. Call lab.runCycle(true) 20 times, take a snapshot, repeat the batch, then call lab.reset(). Compare with lab.runCycle(false). The Set intentionally retains detached panels; this is a controlled demonstration of a bug, not a production pattern. Release the lab instance afterwards.
Regression tests and acceptance criteria
resources.test.cjs
const { test } = require("node:test");
const assert = require("node:assert/strict");
const { subscribe } = require("./dist/resources.js");
test("subscription stops after disposal", () => {
// Given
const target = new EventTarget();
let calls = 0;
const dispose = subscribe(target, "change", () => {
calls += 1;
});
target.dispatchEvent(new Event("change"));
// When
dispose();
dispose();
target.dispatchEvent(new Event("change"));
// Then
assert.equal(calls, 1);
});
The GWT (Given, When, Then) test checks that a disposed subscription no longer calls its callback; repeated cleanup should be harmless. The package also tests repeated mounts, cache capacity, overwriting and rejection of cancelled work. These verify contracts, not garbage collection.
In browser tests repeat the scenario with the same data, track active subscriptions and compare snapshots. Do not make unit tests depend on GC timing or identical memory consumption in CI. Identify the owner of every resource during review, then close the issue only after reproducing the fixed scenario.
