Open a reporting dashboard, switch between a few reports, preview some images and return to the original screen. Everything looks exactly as it did when you started. Yet the browser is using more memory.
Do it another twenty times and the application begins to feel sluggish. On a laptop with plenty of RAM, you might barely notice. On a mobile device, the same behaviour could make the browser struggle to keep the page alive.
The instinctive reaction is to blame React, the garbage collector or the size of the API response. Sometimes one of those is involved. But a more useful place to start is asking a different question: what is still holding on to the data?
JavaScript manages memory automatically, but we still design the lifetimes of the objects and resources our applications create.
1. Garbage collection doesn't understand your business logic
Consider a dashboard that stores previously opened reports for quick access.
const reportHistory = new Map();
async function openReport(id) {
const response = await fetch(`/api/reports/${id}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const report = await response.json();
reportHistory.set(id, report);
return report;
}
When the user closes a report, the report component disappears. But its data is still referenced by the module-level Map. If the module remains reachable, so do the reports it holds.
Modern JavaScript garbage collectors use reachability as a basis for determining which objects may be reclaimed. An object that can still be reached through a live reference is not necessarily useful; it is simply still accessible.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="245" viewBox="0 0 760 245" role="img" aria-label="What keeps a report reachable?">
<rect x="0" y="0" width="760" height="245" rx="6" fill="#f6f4ee" stroke="none"/><text x="24" y="34" fill="#242b25" font-family="Arial, sans-serif" font-size="21" text-anchor="start">What keeps a report reachable?</text>
<rect x="24" y="65" width="190" height="52" rx="6" fill="#fffef9" stroke="#d9ddd2"/><text x="119.0" y="96.0" fill="#242b25" font-family="Arial, sans-serif" font-size="15" text-anchor="middle">Live module</text><rect x="285" y="65" width="190" height="52" rx="6" fill="#e6eadd" stroke="#242b25"/><text x="380.0" y="96.0" fill="#242b25" font-family="Arial, sans-serif" font-size="15" text-anchor="middle">Map entry</text><rect x="546" y="65" width="190" height="52" rx="6" fill="#e6eadd" stroke="#242b25"/><text x="641.0" y="96.0" fill="#242b25" font-family="Arial, sans-serif" font-size="15" text-anchor="middle">Report data</text><line x1="214" y1="91" x2="285" y2="91" stroke="#6d7268" stroke-width="1.5"/><line x1="475" y1="91" x2="546" y2="91" stroke="#ab4932" stroke-width="1.5"/><rect x="24" y="153" width="190" height="48" rx="6" fill="#fffef9" stroke="#d9ddd2"/><text x="119.0" y="182.0" fill="#242b25" font-family="Arial, sans-serif" font-size="15" text-anchor="middle">Closed component</text><text x="285" y="176" fill="#6d7268" font-family="Arial, sans-serif" font-size="13" text-anchor="start">Component removal does not break the Map reference.</text><text x="24" y="227" fill="#6d7268" font-family="Arial, sans-serif" font-size="13" text-anchor="start">Remove the entry when its owner no longer needs the report.</text>
</svg>Setting a local variable to null does not help if another reference remains:
let report = await openReport(123);
report = null;
console.log(reportHistory.has(123)); // true
Removing the entry breaks that particular reference:
reportHistory.delete(123);
The object becomes eligible for collection if nothing else retains it. This doesn't guarantee immediate reclamation or an immediate drop in the operating system's memory readings.
For metadata tied to the lifetime of an object, WeakMap is sometimes a better fit:
const rowMetadata = new WeakMap();
function getRowMetadata(row) {
if (!rowMetadata.has(row)) {
rowMetadata.set(row, { selected: false });
}
return rowMetadata.get(row);
}
The map alone won't keep an otherwise unreachable object key alive. This is useful for metadata associated with DOM elements or other objects, but not a replacement for a cache keyed by ordinary string IDs. Nor does it provide a predictable eviction schedule.
See the ECMAScript WeakMap specification and MDN's memory management guide.
2. Closing a component doesn't necessarily close its resources
A React component might subscribe to resize events, receive socket messages or start a polling timer. These resources can outlive the component if their owner doesn't clean them up.
Here is a simple report preview:
import { useEffect } from 'react';
function ReportPreview({ report }) {
useEffect(() => {
function onResize() {
console.log(report.id, window.innerWidth);
}
window.addEventListener('resize', onResize);
}, [report]);
return <h2>{report.title}</h2>;
}
Every time the report reference changes, the Effect registers another listener. It never removes the previous one. Each listener closes over its report, potentially keeping that report reachable even after the screen is gone.
The fix is not to stop React rendering. It is to give the listener a matching cleanup operation.
useEffect(() => {
function onResize() {
console.log(report.id, window.innerWidth);
}
window.addEventListener('resize', onResize);
return () => {
window.removeEventListener('resize', onResize);
};
}, [report]);
You can also avoid capturing the entire report if the listener only needs its ID:
const reportId = report.id;
useEffect(() => {
const controller = new AbortController();
window.addEventListener('resize', () => {
console.log(reportId, window.innerWidth);
}, { signal: controller.signal });
return () => controller.abort();
}, [reportId]);
The same ownership principle applies to other resources:
| Resource | Matching cleanup |
|---|---|
| Interval | clearInterval() |
| ResizeObserver | disconnect() |
| WebSocket owned by the component | close() |
| Shared socket subscription | Remove that subscription, not the entire socket |
| Dedicated worker owned by the component | terminate() |
| Object URL | URL.revokeObjectURL() when no longer needed |
React runs Effect cleanup before rerunning an Effect with changed dependencies and when the component unmounts. Development Strict Mode can expose missing cleanup by exercising an additional setup and cleanup cycle. See React's useEffect reference.
Not every asynchronous operation that completes after unmount is a memory leak. A short-lived promise may settle and release its references naturally. Look for resources that remain registered or reachable longer than intended.
3. Your cache may have an expiration policy but no memory budget
Caching search results sounds reasonable. Users often repeat a search, so why fetch the same results again?
const results = new Map();
function rememberSearch(query, data) {
results.set(query, {
data,
expiresAt: Date.now() + 60_000
});
}
The timestamp doesn't remove anything. Unless you revisit a key or explicitly prune the cache, expired entries remain in memory.
Imagine 5,000 distinct searches, each retaining approximately 100 KiB of data. That represents about 488 MiB of payloads alone, assuming independent allocations of that size. Actual JavaScript memory may be higher or lower depending on representation, sharing and runtime overhead. This is an illustrative calculation, not a benchmark.
A small cache needs at least two policies: when data stops being fresh and how much data may remain resident.
export function createCache({ ttl = 60_000, maxEntries = 100 } = {}) {
if (!Number.isFinite(ttl) || ttl < 0) {
throw new RangeError('Invalid TTL');
}
if (!Number.isInteger(maxEntries) || maxEntries < 1) {
throw new RangeError('Invalid maximum entry count');
}
const entries = new Map();
function prune() {
const now = Date.now();
for (const [key, entry] of entries) {
if (entry.expiresAt <= now) entries.delete(key);
}
}
return {
get(key) {
const entry = entries.get(key);
if (!entry) return undefined;
if (entry.expiresAt <= Date.now()) {
entries.delete(key);
return undefined;
}
entries.delete(key);
entries.set(key, entry);
return entry.data;
},
set(key, data) {
prune();
entries.delete(key);
entries.set(key, { data, expiresAt: Date.now() + ttl });
while (entries.size > maxEntries) {
entries.delete(entries.keys().next().value);
}
},
prune,
clear() { entries.clear(); },
get size() { return entries.size; }
};
}
This combines TTL with least-recently-used eviction. Reads update the entry's position; writes prune expired entries and enforce the capacity. It deliberately does not create another background timer. An idle cache can retain expired entries until a later access, explicit prune or clear.
A count limit is not a byte limit. A hundred large video buffers can be much more expensive than a hundred small settings objects. For workloads with variable payload sizes, introduce a weight budget or use a tested size-aware cache implementation.
Also account for every layer of caching. React Query, a module-level Map and a worker's dataset might all retain representations of the same report. Some references may share the same underlying object, but copying or serialization can create additional allocations.
Related Buildworthy article: How a Simple JavaScript Cache Can Prevent Duplicate API Requests.
4. A small view can keep a large allocation alive
A reporting application downloads a binary export and retains just its header for later inspection.
function readHeader(buffer) {
const bytes = new Uint8Array(buffer);
return bytes.subarray(0, 32);
}
subarray() returns a view, not an independent copy. If the original backing buffer is 64 MiB, the tiny 32-byte view can keep that backing allocation alive.
If you need only those 32 bytes, make a copy instead:
function readHeader(buffer) {
const bytes = new Uint8Array(buffer);
return bytes.slice(0, 32);
}
SVG source
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="250" viewBox="0 0 760 250" role="img" aria-label="A tiny view can retain a large buffer">
<rect x="0" y="0" width="760" height="250" rx="6" fill="#f6f4ee" stroke="none"/><text x="24" y="34" fill="#242b25" font-family="Arial, sans-serif" font-size="21" text-anchor="start">A tiny view can retain a large buffer</text>
<text x="24" y="65" fill="#242b25" font-family="Arial, sans-serif" font-size="15" text-anchor="start">subarray(): shared backing allocation</text><rect x="24" y="82" width="712" height="42" rx="6" fill="#e6eadd" stroke="#242b25"/><rect x="24" y="82" width="9" height="42" rx="6" fill="#ab4932" stroke="none"/><text x="380" y="108" fill="#242b25" font-family="Arial, sans-serif" font-size="15" text-anchor="middle">64 MiB backing buffer</text><text x="24" y="146" fill="#ab4932" font-family="Arial, sans-serif" font-size="13" text-anchor="start">32-byte view (highlight enlarged for visibility)</text><text x="24" y="181" fill="#242b25" font-family="Arial, sans-serif" font-size="15" text-anchor="start">slice(): independent copy</text><rect x="24" y="194" width="110" height="32" rx="6" fill="#e6eadd" stroke="#242b25"/><text x="79" y="215" fill="#242b25" font-family="Arial, sans-serif" font-size="13" text-anchor="middle">32 bytes</text><text x="155" y="215" fill="#6d7268" font-family="Arial, sans-serif" font-size="13" text-anchor="start">Original buffer can be collected if no other references remain.</text>
</svg>The copy has a cost, but it may let the original buffer become collectible once all its other references disappear. Node.js Buffer has its own slicing semantics: do not assume Buffer.slice() makes a copy. Use an explicit copying operation such as Buffer.from(existingBuffer.subarray(0, 32)) when you need independent bytes.
Images introduce a different resource lifetime. A file preview created with URL.createObjectURL(file) remains associated with the Blob until the URL is revoked or its environment is unloaded. In a long-lived single-page application, repeatedly creating preview URLs without revoking them can be expensive.
import { useEffect, useState } from 'react';
function FilePreview({ file }) {
const [preview, setPreview] = useState(null);
useEffect(() => {
if (!file) {
setPreview(null);
return;
}
const url = URL.createObjectURL(file);
setPreview({ file, url });
return () => URL.revokeObjectURL(url);
}, [file]);
if (!file || preview?.file !== file) return null;
return <img src={preview.url} alt="Selected file preview" />;
}
Revoking on cleanup keeps the resource available while it is displayed rather than invalidating the URL immediately after an image loads.
Another example is a detached DOM subtree: removing an element from the document does not free it if a long-lived registry still references it. A map of old modal elements can unintentionally retain their descendants. Delete registry entries when their elements are destroyed, or use weakly keyed metadata where appropriate.
5. High memory usage isn't always a memory leak
A search results screen can allocate a new array on every keystroke:
const visible = rows
.filter(row => row.name.includes(query))
.map(row => ({ id: row.id, label: row.name }));
Even if every previous array becomes unreachable, the application may allocate objects faster than the collector can conveniently reclaim them. Frequent collection can contribute to latency. This is allocation churn, distinct from a growing collection of objects that never become unreachable.
Conversely, keeping one enormous dataset in memory can cause sustained memory pressure even if nothing leaks. This is memory bloat. Virtualising a list can reduce DOM and rendering costs, but it does not automatically reduce the size of the underlying JavaScript dataset. Pagination or incremental processing may be needed as well.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="260" viewBox="0 0 760 260" role="img" aria-label="Memory growth has different causes">
<rect x="0" y="0" width="760" height="260" rx="6" fill="#f6f4ee" stroke="none"/><text x="24" y="34" fill="#242b25" font-family="Arial, sans-serif" font-size="21" text-anchor="start">Memory growth has different causes</text>
<text x="24" y="61" fill="#6d7268" font-family="Arial, sans-serif" font-size="13" text-anchor="start">Conceptual heap readings across repeated actions</text><rect x="24" y="78" width="220" height="136" rx="6" fill="#fffef9" stroke="#d9ddd2"/><text x="134" y="101" fill="#242b25" font-family="Arial, sans-serif" font-size="14" text-anchor="middle">Stable baseline</text><line x1="44" y1="185" x2="224" y2="185" stroke="#d9ddd2" stroke-width="1.5"/><line x1="44" y1="122" x2="44" y2="185" stroke="#d9ddd2" stroke-width="1.5"/><polyline points="49,153 77,128 105,153 133,128 161,153 189,128 217,153" fill="none" stroke="#242b25" stroke-width="2"/><rect x="270" y="78" width="220" height="136" rx="6" fill="#fffef9" stroke="#d9ddd2"/><text x="380" y="101" fill="#242b25" font-family="Arial, sans-serif" font-size="14" text-anchor="middle">Rising baseline</text><line x1="290" y1="185" x2="470" y2="185" stroke="#d9ddd2" stroke-width="1.5"/><line x1="290" y1="122" x2="290" y2="185" stroke="#d9ddd2" stroke-width="1.5"/><polyline points="295,169 323,149 351,162 379,139 407,151 435,128 463,137" fill="none" stroke="#ab4932" stroke-width="2"/><rect x="516" y="78" width="220" height="136" rx="6" fill="#fffef9" stroke="#d9ddd2"/><text x="626" y="101" fill="#242b25" font-family="Arial, sans-serif" font-size="14" text-anchor="middle">High stable baseline</text><line x1="536" y1="185" x2="716" y2="185" stroke="#d9ddd2" stroke-width="1.5"/><line x1="536" y1="122" x2="536" y2="185" stroke="#d9ddd2" stroke-width="1.5"/><polyline points="541,137 569,128 597,137 625,128 653,137 681,128 709,137" fill="none" stroke="#242b25" stroke-width="2"/><text x="24" y="242" fill="#6d7268" font-family="Arial, sans-serif" font-size="13" text-anchor="start">Patterns are diagnostic clues, not proof of a leak.</text>
</svg>A healthy heap often rises and falls as the runtime allocates and collects objects. A rising baseline after comparable work and collection is more suspicious than a single peak. A stable high baseline can also deserve investigation. None of these shapes alone proves a leak.
In Node.js, total process memory and JavaScript heap usage are different measurements:
const mib = bytes => Math.round(bytes / 1024 / 1024);
const memory = process.memoryUsage();
console.table(Object.fromEntries(
Object.entries(memory).map(([key, value]) => [key, mib(value)])
));
heapUsed measures used V8 heap memory; heapTotal describes allocated V8 heap space. rss measures resident process memory, including native allocations and code. external includes native memory associated with JavaScript objects; arrayBuffers is included in that figure. Don't add these fields together as if they were independent totals.
A process can retain a high RSS even when the JavaScript heap stabilizes, due to native allocation behaviour or fragmentation. Use the right metric before deciding to increase the heap limit. See Node.js process.memoryUsage.
6. Find the object that refuses to leave
The easiest way to investigate a suspected browser memory leak is to reproduce the same lifecycle several times, rather than inspect a random snapshot of a busy application.
Use Chrome DevTools:
- Start with a production build in a clean browser session. Open the screen you want to investigate and allow initial loading to settle.
- Open the Memory panel. Take a heap snapshot as a baseline.
- Open and close a report, return to the same screen and repeat the cycle ten or twenty times. Wait for background requests to finish.
- Take another heap snapshot under comparable conditions. Use the Comparison view to examine growing object counts and retained sizes.
- Inspect the Retainers panel for a representative object. Follow the reference chain toward its root. Look for a long-lived Map, listener, timer, closure or subscription that should no longer own it.
- Fix that ownership issue and repeat the experiment. Check whether the relevant object counts and post-collection baseline stop increasing.
Shallow size is the memory attributed directly to an object. Retained size is an estimate of memory that would become collectible if that object were removed from the relevant reference graph. A small object with a large retained size can be a useful clue, but shared references complicate interpretation.
The Allocation instrumentation on timeline profile helps investigate allocation churn. The Detached elements profile helps identify removed DOM elements that are still referenced. Avoid logging large objects during experiments: DevTools itself can retain inspected objects and distort your observations.
For a minimal controlled reproduction, paste the following into a local development page rather than a production application:
const retainedReports = [];
function reproduce() {
const report = Array.from({ length: 2000 }, (_, id) => ({
id,
description: `Report row ${id}`
}));
retainedReports.push(report);
}
for (let i = 0; i < 20; i++) reproduce();
// Compare snapshots before and after dropping references.
// Run separately, after taking the first snapshot:
retainedReports.length = 0;
This deliberately retains objects until the array is cleared. Actual collection timing and measured memory vary. Chrome's heap snapshot documentation and memory troubleshooting guide explain the relevant tools.
Final thoughts
When an application becomes slow after hours of use, it is tempting to add memoisation, increase the Node.js heap limit or introduce a more powerful server. Those changes may postpone the symptom without fixing the underlying issue.
A better starting point is to define who owns each resource, how long it should live and what releases it. Give caches a capacity. Remove subscriptions. Close resources. Avoid keeping large allocations alive through small views. Measure memory across repeated, equivalent user interactions.
Garbage collection manages the lifetime of unreachable objects. Designing when objects should become unreachable is still our responsibility.
THE CONVERSATION
Comments
Questions, useful examples and different approaches are welcome. Keep the discussion thoughtful and on topic.
Loading comments…