Visual Debugging for Memory Leaks
Memory Lens (MemLens) is a utility tool that helps visually debug memory leaks in web browsers. It highlights detached DOM elements still retained in memory and leaking React components with an overlay, allowing you to identify leaked elements right after interactions and trace their retainer paths in the browser’s DevTools using memory IDs annotated by MemLens.
You can use MemLens in two ways:
- Manually copy and paste MemLens’ code into the browser console to debug leaks in the current page.
- Run MemLens through MemLab.
The sections below explain how to use MemLens for browser memory leak debugging.
Manually Running MemLens in a Browser
- Copy and paste the MemLens bundle code into your browser’s console (close DevTools to avoid leaks caused by Chrome DevTools).
- Interact with the page without triggering a full refresh, as a hard refresh clears the entire JS heap and makes leak debugging unnecessary.
- When MemLens outlines possible memory leaks, take a heap snapshot and search for the displayed memory IDs.
To build the bundle yourself, clone the
MemLab repository,
run npm run build
, and copy the MemLens bundle code from
packages/lens/dist/memlens.run.bundle.min.js
or
packages/lens/dist/memlens.run.bundle.js
.
The screen recording below demonstrates how to use MemLens on a web page.
Once MemLens is active, it tracks React components that leak DOM elements and outlines them on the page. Each outline includes a memory ID. Hover over the outline to view the memory ID and the corresponding React component stack, or click to pin it.
With the memory ID, take a heap snapshot in Chrome DevTools and search for it in the Memory panel. This will reveal the leaked component’s retained path in the JS heap, helping you understand why it remains in memory.
Note: The target page should ideally be a React app serving minified JS code. When searching for the memory ID in Chrome DevTools, the detached DOM element’s retainer path will also appear minified.
Using MemLens with MemLab
MemLens can also run during MemLab executions in headful mode to display leak outlines:
memlab run --scenario your_test_scenario_file_path.js --headful --display-leak-outlines
--headful
: Runs the browser in visible mode so you can see the UI.--display-leak-outlines
: Enables MemLens to track and display outlines of leaked components in the test page.
If you want to pause a MemLab run at steps defined in your scenario file
and interact with MemLens in the headful browser session, use the --debug
option. This pauses automated browser actions before each step until you
press Enter in the terminal.