Agustin Barrientos
All posts

Finding a Memory Leak in a Removed Component With Chrome DevTools

Want more of these in your Google results?

Memory leaks are pretty easy to miss in a web app. As developers, we frequently reload the pages we’re building, and whatever the page had in memory goes away with each reload.

The thing is, a lot of pages don’t get reloaded for a long time. Some users leave tabs open for days, or even weeks.

Open tabs also share the computer’s memory. A page that keeps growing leaves less for the others. To free some of it, Chrome’s Memory Saver deactivates the tabs you aren’t using and reloads each one when you go back to it.

I have to warn you that this article is heavier and harder than most on this site. But understanding this concept is a fundamental skill for a web developer, and the demos let you follow along in your own DevTools.

For this article, I made a small files app.

Clicking a file opens a preview over the list, Left and Right move to the previous or next file, and Escape closes it.

To catch those keys, the preview listens for them on the whole window, and it never removes that listener. So after the preview closes, the browser can’t free it, or anything inside it, because the window’s listener still points at it.

Browsers free the memory nothing points at anymore (that’s called garbage collection), but they do it on their own schedule. MDN’s guide to memory management says page code has no way to start it.

MDN and web.dev both mention a forgotten event listener as a common cause of memory leaks. Anything else that outlives the preview and points at it keeps it in memory too, like a timer or an open WebSocket.

I’ll teach you how to use the Memory panel in Chrome DevTools to find what’s keeping the closed previews in memory, fix the leak, and make sure the fix still works when the preview moves to a side panel. After that, I’ll go through where the cleanup goes in Angular, React, and Vue.

I’d check for this in any component people open and close a lot, like a menu, a popover, or a preview.

Seeing the leak in a heap snapshot

You don’t learn much from opening and closing the preview a single time.

Leak or not, the browser doesn’t free a closed preview right away. Chromium often takes more than 15 seconds, unless something forces a garbage collection. And code running for the first time leaves a few things behind for the next runs, like the compiled version of its functions.

The test is to open and close it a few times in a row, then compare the memory before and after. In this article, a round means opening and closing the preview three times. DevTools’ own docs recommend rounds too. They define a memory leak as a bug where a page uses more and more memory over time.

You compare the memory with heap snapshots, in the Memory panel of DevTools. A heap snapshot is a list of the objects the page’s JavaScript can reach, grouped by what created them. Every snapshot starts with a garbage collection, which means anything in the list survived it.

You’ll find the preview in the list by its tag, <file-preview>.

Since page code can’t take heap snapshots, the Memory panel under the files app below is a drawing, with numbers driven by your clicks. To follow along in your DevTools, open the demo in a separate tab, where the drawing goes away.

These are the steps for the first round:

  1. Click ⁠Take snapshot⁠ in the demo below.
  2. Open Beach July and press Escape to close it. Do it three times.
  3. Take Snapshot 2 by pressing the Take heap snapshot button at the top left of the panel.
  4. Type “file-preview” in ⁠Filter by class⁠.

Snapshot 2 has a Detached <file-preview> row with a count of 3. Those are the three previews you closed, still in memory even though they’re out of the page. Snapshot 1 doesn’t have that row, because you took it before opening any preview.

DevTools’ docs use “detached” for a node that’s out of the page while some JavaScript keeps a reference to it.

Chrome’s Task Manager shows the memory growing while you click, in the number in parentheses in the JavaScript memory column. You add it by right-clicking a column header. DevTools’ Performance monitor shows the growth too, with its ⁠JS event listeners⁠ chart turned on.

But both of them count garbage the browser hasn’t collected yet. Even without a leak, their numbers often stay high until the next garbage collection. Clicking the Collect garbage button in the Memory panel starts one right away.

They’re good for noticing something growing.

Heap snapshots show what stayed, along with a Retainers pane for what’s holding it.

Why two snapshots aren’t enough

Compared across two snapshots, something the app keeps on purpose looks just like a leak. That includes a cache holding one closed preview, and the preview you have open right now.

That’s why it’s a good idea to take a third snapshot.

Under ⁠All objects⁠, the count for your tag shows whether something grows. If it goes up by one per preview you opened, memory keeps growing with every round.

The Filter menu’s ⁠Objects allocated between Snapshot 1 and Snapshot 2⁠ shows which of those objects stayed. Each object gets a number the first time a snapshot sees it and keeps that number in later snapshots. The filter lists the objects numbered in Snapshot 2 that are in the snapshot you selected. Later rounds never add to that list.

By Snapshot 3, those objects have had a whole extra round to go away. Anything the filter lists there survived it.

A count that stays at 1 under ⁠All objects⁠, however many rounds you run, means something keeps exactly one preview. The Retainers pane shows whether it’s on purpose, like a cache.

Next, run a second round in the files app above, opening and closing Beach July three more times. Then take a third snapshot. Type “file-preview” in ⁠Filter by class⁠ again, since a new snapshot starts with an empty filter.

Snapshot 3 has 6 under ⁠All objects⁠, up from 3 in Snapshot 2. Now switch the Filter menu from ⁠All objects⁠ to ⁠Objects allocated between Snapshot 1 and Snapshot 2⁠. It leaves the 3 previews from the first round, the ones that survived the second.

The filtered list is never empty, even in correct code, because compiled code and other engine objects from the first round stay in it.

Typing your tag in ⁠Filter by class⁠ hides those.

Closed previews also hold on to the elements inside them. To see those, pick ⁠All objects⁠ and type “Detached” in place of “file-preview”. You’ll get rows like Detached <header> and Detached <button>, 16 elements per closed preview.

Next to heap snapshots, real DevTools has a Detached elements profile in the Memory panel. It lists the closed previews and their node counts, but to see what’s holding them, you need a heap snapshot.

Firefox’s Memory tool and the Timelines tab in Safari’s Web Inspector have a version of this check.

Following the Retainers pane

Back in the Memory panel, expand Detached <file-preview> and click one of its rows. The Retainers pane under the list shows what’s pointing at the preview you picked.

DevTools opens the shortest path from the preview back to a root (something the browser keeps alive no matter what, like the window). Rows start with the reference, followed by in and the object holding it.

From the top, here’s what the rows mean:

  • this in system / Context / scope stands for the variables a function kept from where it was created, with the preview as their this.
  • context in handleKeydown() means the function is the preview’s keydown handler.
  • V8EventListener and the next few rows are the browser’s record of the listener and of the lists it’s stored in. V8 and Blink are the parts of Chrome running the JavaScript and rendering the page.
  • blink::EventTargetData holds an object’s listeners.
  • Window and the page’s address show whose listeners they are.
  • At the bottom, the chain ends at the global object and at (GC roots), DevTools’ name for the roots.

Read from the bottom up, handleKeydown is one of the window’s keydown listeners, and it holds the preview.

The preview is a custom element (a tag you define with a JavaScript class). The browser calls the class’s connectedCallback() once the element is in the page. Right after the element is removed, it calls disconnectedCallback().

My first version of the preview adds handleKeydown to the window in connectedCallback() and doesn’t have a disconnectedCallback(). On Escape, the handler calls remove() on the preview.

file-preview.js
// file-preview.js
class FilePreview extends HTMLElement {
	handleKeydown = ( event ) => {
		if ( event.key === 'Escape' ) {
			this.remove();
		}
	};

	connectedCallback() {
		window.addEventListener( 'keydown', this.handleKeydown );
	}
}

customElements.define( 'file-preview', FilePreview );

Real DevTools links the context in handleKeydown() row to the handler’s code in the Sources panel. On a production build like this site’s, that link opens a minified file at line 1.

Searching your code for the function’s name is faster.

The Filter menu has a shortcut for leaks like this one, ⁠Objects retained by event handlers⁠. It lists the objects kept in memory by nothing but event handlers. With “file-preview” in ⁠Filter by class⁠, it shows the 6 closed previews. Without the class filter, the list includes objects DevTools’ scripts add to the page.

On the demo page, opened in a separate tab, the Console’s getEventListeners( window ) lists the window’s listeners by event type. You’ll see one keydown entry per listening preview.

What keeps a removed component in memory

The garbage collector starts at the roots and frees whatever it can’t get to from them.

A page’s roots are the window and the document with its nodes, plus the code running right now. Work the browser has left to do for the page counts too, like a running timer or an unfinished request.

Observers are kept by the node they watch. For example, an observer on document.body keeps its callback, and whatever the callback uses, while the body is in the page.

That means a removed component stays in memory only while a path from one of those roots reaches it.

Leaks like this one have a path that goes through something the component added to an object that outlives it. References inside the component don’t keep it.

Listeners on the component’s own element don’t keep it either, and neither do observers on its nodes or promises nothing outside can resolve. Those go away together with the component, in all three browser engines.

Chromium has one exception, an IntersectionObserver created with a root. While that root is in the page, the observer keeps the component, as long as its callback can reach it. It happens even for an observer watching nothing but the component’s element. I’d disconnect that one in the cleanup.

These are the usual things a component adds to objects that outlive it, and how to undo them.

Table What a component can register on objects that outlive it, and how to undo it.
Kept byExampleUndo it with
A listenerkeydown on window, or a listener on a shared event busremoveEventListener() with the same function, or aborting its signal
A timersetInterval(), or a requestAnimationFrame() callback that schedules itself againclearInterval() or cancelAnimationFrame()
An observerResizeObserver or MutationObserver on document.bodydisconnect()
A connectionAn open WebSocket, EventSource, or BroadcastChannel with a message listenerclose()
A requestA long poll with fetch() that never answers, with a callback that uses the componentabort() on its controller
A storestore.subscribe( render ) on a store the whole app sharesThe unsubscribe function the store returns
A listopenPreviews.add( this ) at the top of a moduleDeleting the entry, or a WeakMap keyed by the element when you only look things up
A variable$lastTitle = $title, holding one of its nodesClearing the variable
Sources: the HTML spec’s sections on BroadcastChannel and server-sent events, which warn about the first and require browsers to keep an open EventSource with listeners alive, and the WebSockets standard, which does the same for WebSocket. Every row keeps a removed component in memory in Chromium, Firefox, and WebKit.

One node in a variable keeps its whole tree, since nodes point at their parents and their children. And for a custom element, that tree includes the element itself.

Modal dialogs keep the focus inside them. Their keydown listener goes on the dialog itself, with no window listener to undo.

This preview isn’t modal. Its keys have to work wherever the focus is on the page, which is why it listens on the window.

That doesn’t include iframes, though. After a click inside one, like Lease March’s document in the docking demos further down, the keys go to the iframe’s document and never reach the window listener.

Fixing it with an AbortController

To fix the preview, I’d use an AbortController. It’s an object whose abort() method cancels whatever you gave its signal to.

Here, connectedCallback() creates one and passes its signal to the window listener, while disconnectedCallback() calls abort().

Calling abort() takes off the listeners that got its signal. That’s because the DOM spec’s steps for adding a listener set up the removal at the same time they add the listener.

file-preview.js
// file-preview.js
#controller;

connectedCallback() {
	this.#controller = new AbortController();
	window.addEventListener( 'keydown', this.handleKeydown, { signal: this.#controller.signal } );
}

disconnectedCallback() {
	this.#controller.abort();
}

An aborted signal stays aborted. Since the browser calls connectedCallback() whenever the element is added to a page, each call has to create a new controller and keep it in the private #controller field.

Using removeEventListener() would work here too, because the class field holds one function for the element’s whole life. To remove a listener, the browser needs the exact function it got.

Timers and store subscriptions don’t take a signal, but you can stop them from a listener on the signal’s abort event.

For example, if the preview refreshed the link to its file once a minute and showed comments from a store the whole app shares, the setup would look like this:

file-preview.js
// file-preview.js
connectedCallback() {
	this.#controller = new AbortController();
	const { signal } = this.#controller;
	window.addEventListener( 'keydown', this.handleKeydown, { signal } );

	const timer = setInterval( () => this.refreshLink(), 60000 );
	signal.addEventListener( 'abort', () => clearInterval( timer ) );

	const unsubscribe = store.subscribe( () => this.showComments() );
	signal.addEventListener( 'abort', () => unsubscribe() );
}

Requests are easier. Passing the signal to fetch() in its options stops the request on abort. My router article uses one to stop a load the user left.

Checking that the fix works

Checking the fix takes the same three snapshots.

The files app below has a Code menu of three versions to check with this routine:

  1. Take a snapshot and run a round, opening and closing Beach July three times.
  2. Take another snapshot and run a second round.
  3. Take a third snapshot to finish.
  4. On Snapshot 3, type “file-preview” in ⁠Filter by class⁠ and pick ⁠Objects allocated between Snapshot 1 and Snapshot 2⁠.

With ⁠AbortController⁠, no file-preview row shows up in any snapshot or filter. Any you do see is a preview you left open, listed as <file-preview>, without Detached in front.

The second version, ⁠Remove with bind()⁠, is a pull request that looks like a fix, since it adds a removeEventListener() call. Both calls pass the handler method through bind():

file-preview.js
// file-preview.js
handleKeydown( event ) {
	if ( event.key === 'Escape' ) {
		this.remove();
	}
}

connectedCallback() {
	window.addEventListener( 'keydown', this.handleKeydown.bind( this ) );
}

disconnectedCallback() {
	window.removeEventListener( 'keydown', this.handleKeydown.bind( this ) );
}

But every bind() call makes a new function. The window never got the function that removeEventListener() receives, so nothing comes off.

Its counts go up like the original leak’s, from 0 to 3 to 6, with 3 left in the filter. The first retainer, bound_this in native_bind(), is the bound function holding the preview as its this.

⁠Objects retained by event handlers⁠ doesn’t list these previews. DevTools marks the method as the handler, while the bound copies hold the previews. Check the between filter for this one.

The third version, ⁠Reuses one preview⁠, keeps the element it closed and shows it again for the next file, without ever making a second one. Its counts go from 0 to 1 and stay at 1, with the first round’s preview left in the filter.

Here, the Retainers pane starts at cachedPreview in <files-app>, a field on the files app. The steady 1 is the preview the app keeps on purpose. Its connectedCallback() adds the listener back whenever the app reuses it.

Compare the counts for your tag, since the totals above the list grow even in correct code.

For a quick count, open the Console on the demo page. There, queryObjects( customElements.get( 'file-preview' ) ) runs a full garbage collection and lists the previews in memory, open or closed.

Keep in mind that anything you pass to console.log() while you debug stays reachable through the Console until you clear it or reload, or until newer messages push it out. So do the objects queryObjects() prints.

Clear the Console before the last snapshot. DevTools’ Filter menu has ⁠Objects retained by DevTools Console⁠ for the objects nothing but the Console holds.

When the preview moves

In the files app, clicking ⁠Dock⁠ moves an open preview into a side panel next to the list, without closing it.

Moving an element within the page with appendChild() is, for the browser, a removal followed by an insertion. So is a move with insertBefore().

Custom elements get disconnectedCallback() followed by connectedCallback() on this move, in every engine. Their cleanup runs, then their setup.

Two common versions of the preview break here.

One adds the listener in the constructor and aborts it in disconnectedCallback(). Nothing adds it back, which means the first move takes it off for good.

The other tries to remove the listener with a new bind(). Since nothing comes off, the window gets one more listener per move. Ten moves later, a single key press runs eleven copies of the handler, which stay on the window after the element is gone.

The AbortController version doesn’t have this problem, because its connectedCallback() starts over with a new controller.

You’ll need a keyboard for this one:

  1. Open Lease March with ⁠AbortController⁠ picked in Code, and scroll its document a little. Click ⁠Dock⁠ and press Right.
  2. Switch Code to ⁠Remove with bind()⁠ and open Lease March. Click ⁠Dock⁠ and then ⁠Undock⁠, and press Right once.
  3. Switch Code to ⁠Listener added in the constructor⁠ and open Lease March. Click ⁠Dock⁠ and press Escape.

Each dock printed both callbacks in the console and sent Lease March’s document back to the top.

With ⁠AbortController⁠, Right moved the preview one file, to Budget May. ⁠Remove with bind()⁠ jumped three files, to Taxes April, with three listeners running.

Escape, Left, and Right stopped working in the constructor version the moment the preview was docked.

The Close button kept working, though, because its listener is on the element itself.

Keeping the preview’s state with moveBefore()

This part is optional. With the AbortController version, the preview already survives a move.

Lots of things start over with an appendChild() move, though. Focus goes back to the page’s body, an iframe inside loads a new document, CSS animations start again, running transitions are dropped, an open popover closes, a modal dialog stops being modal, and fullscreen ends.

Calling moveBefore() moves a node without the removal and insertion steps. Focus, an iframe’s document, animations and transitions, popovers, modal dialogs, and fullscreen stay the way they were. You’ll find examples in the announcement post.

Custom elements moved with moveBefore() get disconnectedCallback() and connectedCallback() by default. If the class defines connectedMoveCallback(), even an empty one, the browser calls it in place of the pair. Elements written before moveBefore() existed get that default from the HTML spec.

file-preview.js
// file-preview.js
connectedMoveCallback() {
	// Empty on purpose, because the window listener stays through the move.
}

moveBefore() can’t move a node into the page or out of it, though. It throws a HierarchyRequestError, for example on a preview that hasn’t been added yet.

That’s why the first insertion has to be a normal append(). My movePreview() function below uses moveBefore() if both nodes are in the page and the browser has the method, and append() otherwise.

move-preview.js
// move-preview.js
function movePreview( $preview, $target ) {
	if ( $preview.isConnected && $target.isConnected && 'moveBefore' in $target ) {
		$target.moveBefore( $preview, null );
	} else {
		$target.append( $preview );
	}
}

Window listeners also get the keys people type into text fields. The element in the code panel below skips those by checking event.composedPath()[0].

Try the two kinds of move in the files app below:

  1. Click ⁠Dock⁠ with Lease March open and scrolled a little.
  2. Switch Move with to ⁠moveBefore()⁠. Scroll again and click ⁠Undock⁠.
  3. Turn ⁠connectedMoveCallback⁠ off. The page reloads, keeping ⁠moveBefore()⁠ picked. Open Lease March again and scroll it a little before you click ⁠Dock⁠.
  4. Press Escape.
file-preview.ts
// index.ts
import type { PreviewStep } from './types';

/**
 * Whether a key press started in a place where the reader types text.
 *
 * A listener on the window gets every key pressed on the page, including the ones typed into a text field.
 * `composedPath()[0]` is the element the key started in, even inside an open shadow root, where `event.target` would only name the host.
 *
 * @param event - A key press from anywhere on the page.
 * @returns Whether it came from an `input`, a `textarea`, a `select`, or an editable element.
 */
function isTyping( event: KeyboardEvent ): boolean {
	const $origin = event.composedPath()[ 0 ];
	return $origin instanceof HTMLElement && ( $origin.isContentEditable || $origin.matches( 'input, textarea, select' ) );
}

/**
 * A file preview that pages through files with the arrow keys and closes with Escape, wherever focus is on the page, outside iframes.
 *
 * The app fills the element's light DOM with its header and content.
 * The element never renders markup of its own, which means its callbacks can run again safely.
 * Every time the element is added to the page, `connectedCallback()` adds the window listener with the signal of a new `AbortController`.
 * `disconnectedCallback()` aborts that controller.
 * The class is exported and not registered, so the page calls `customElements.define( 'file-preview', FilePreview )`.
 *
 * @element file-preview
 * @attr file - The id of the file the app is showing in the preview.
 * @fires preview-close - Bubbles when the reader presses Escape or clicks a `[data-action="close"]` button inside the preview.
 * @fires preview-step - Bubbles with `-1` or `1` when the reader presses an arrow key or clicks a `[data-action="previous"]` or `[data-action="next"]` button.
 */
export class FilePreview extends HTMLElement {

	/**
	 * The controller for the current connection, replaced on every connection because an aborted signal stays aborted.
	 */
	#controller?: AbortController;

	/**
	 * Turns Escape into `preview-close` and the left and right arrows into `preview-step`, unless the key started in a text field.
	 *
	 * As an arrow function in a class field, it always runs with the preview as `this`, and it stays the same function for the life of the element.
	 *
	 * @param event - The key press, from anywhere in the page.
	 */
	handleKeydown = ( event: KeyboardEvent ): void => {
		if ( isTyping( event ) ) {
			return;
		}
		if ( event.key === 'Escape' ) {
			this.dispatchEvent( new Event( 'preview-close', { bubbles: true } ) );
		} else if ( event.key === 'ArrowLeft' ) {
			this.step( -1 );
		} else if ( event.key === 'ArrowRight' ) {
			this.step( 1 );
		}
	};

	/**
	 * Turns clicks on the `data-action` buttons inside the preview into the same events the keys fire.
	 *
	 * Its listener is on the preview itself, which means it goes away with the preview and needs no cleanup.
	 *
	 * @param event - The click, from anywhere inside the preview.
	 */
	handleClick = ( event: MouseEvent ): void => {
		const $button = event.target instanceof Element ? event.target.closest( '[data-action]' ) : null;
		const action = $button?.getAttribute( 'data-action' );
		if ( action === 'close' ) {
			this.dispatchEvent( new Event( 'preview-close', { bubbles: true } ) );
		} else if ( action === 'previous' ) {
			this.step( -1 );
		} else if ( action === 'next' ) {
			this.step( 1 );
		}
	};

	/**
	 * Adds the click listener to the element itself.
	 * The HTML spec suggests setting up event listeners in a custom element's constructor.
	 */
	constructor() {
		super();
		this.addEventListener( 'click', this.handleClick );
	}

	/**
	 * Creates this connection's controller and listens for keys on the window with its signal.
	 */
	connectedCallback(): void {
		this.#controller = new AbortController();
		window.addEventListener( 'keydown', this.handleKeydown, { signal: this.#controller.signal } );
	}

	/**
	 * Aborts this connection's controller, which removes the window listener.
	 */
	disconnectedCallback(): void {
		this.#controller?.abort();
	}

	/**
	 * Keeps the window listener in place when `moveBefore()` moves the preview.
	 *
	 * When the class defines this method, even empty, `moveBefore()` calls it instead of `disconnectedCallback()` and `connectedCallback()`.
	 * A move with `append()` or `insertBefore()` still runs the other two, which the controller already handles.
	 */
	connectedMoveCallback(): void {}

	/**
	 * Asks the app for the previous or the next file.
	 *
	 * @param step - `-1` for the previous file, `1` for the next one.
	 */
	step( step: PreviewStep ): void {
		this.dispatchEvent( new CustomEvent<PreviewStep>( 'preview-step', { bubbles: true, detail: step } ) );
	}
}

/**
 * Moves the preview to the end of another container, keeping its state where the browser can.
 *
 * `moveBefore()` keeps focus, an iframe's document, and running animations, but it throws a `HierarchyRequestError` if it would move a node into the page or out of it.
 * Where it's missing, `append()` takes the preview out and puts it back in, which runs both callbacks.
 * A preview that isn't in the page yet goes through `append()` as well, which runs only `connectedCallback()`.
 *
 * @param $preview - The preview to move.
 * @param $target - The container that receives it.
 */
export function movePreview( $preview: Element, $target: Element ): void {
	if ( $preview.isConnected && $target.isConnected && 'moveBefore' in $target ) {
		$target.moveBefore( $preview, null );
	} else {
		$target.append( $preview );
	}
}
The panel shows the preview element. The files app, the docking, and the console around it are demo code, and a small subclass of the element prints each callback. Turning the connectedMoveCallback switch off reloads the page, which then defines the element without that method.

The appendChild() dock printed both callbacks and iframe load, with the document back at the top. The moveBefore() undock printed connectedMoveCallback and nothing else. Lease March’s document stayed where you’d scrolled it.

With the switch off, the dock printed both callbacks but no iframe load. The browser kept the document, but the element ran its pair anyway.

Escape printed disconnectedCallback alone, since closing removes the preview for good.

Browser supportmoveBefore()73% of users
Chrome133
Edge133
Firefox144
SafariNo
Safari iOSNo
Chrome Android133

Browser data updated November 12, 2026

Without moveBefore() in Safari, movePreview() appends. There, the iframe reloads, but the element’s cleanup survives the pair.

Where browsers and frameworks differ

These details only matter in a few cases, like a component with a shadow root or one inside a framework.

Some things don’t change under moveBefore(). Playing videos keep playing through a plain move, as long as they’re put back right away. Text selection, on the other hand, collapses either way.

Firefox keeps less with moveBefore() inside a moved element’s shadow root (the separate tree of nodes some components put their markup in). Inside it, an iframe reloads, an animation starts over, and a custom element gets the pair whether or not it defines connectedMoveCallback(), according to the shared browser test results. Since the preview doesn’t have a shadow root, its iframe keeps its document in Firefox too.

None of the frameworks calls moveBefore(). Angular’s renderer moves nodes through insertBefore(). React added the method behind a flag and later turned it off, while Vue’s pull request to use it in <Teleport> is still open.

Lit components extend a base class called LitElement, which doesn’t define connectedMoveCallback() either. So a Lit component you move with moveBefore() gets both callbacks, unless you define connectedMoveCallback() yourself.

Where frameworks run the cleanup

With a framework, you don’t call the cleanup yourself. It removes the component and runs whatever cleanup you gave it.

In Angular, a window listener declared in host comes off when Angular destroys the component. Anything else, like the interval in the component below, goes in a cleanup you register with DestroyRef.

file-preview.component.ts
// file-preview.component.ts
@Component( {
	selector: 'app-file-preview',
	template: '<ng-content />',
	host: { '(window:keydown)': 'onKeydown( $event )' },
} )
export class FilePreviewComponent {
	constructor() {
		const timer = setInterval( () => this.refreshLink(), 60000 );
		inject( DestroyRef ).onDestroy( () => clearInterval( timer ) );
	}

	// onKeydown() and refreshLink() follow.
}

Angular cleans up the template’s listeners and the effects created in the component for you. Both the async pipe and toSignal() unsubscribe automatically.

Listeners you add with Renderer2.listen() are different, since they stay until you call the function it returns.

And takeUntilDestroyed() only unsubscribes what you pipe through it. Outside an injection context (code where inject() works, for example the constructor above or a field initializer), it needs a DestroyRef passed in.

In React, the function an effect returns is its cleanup. React runs it before the effect’s next setup and once the component is removed. It’s the only cleanup React runs for what the effect added.

This version of the preview gets an onClose prop and calls it on Escape:

FilePreview.jsx
// FilePreview.jsx
useEffect( () => {
	const controller = new AbortController();
	window.addEventListener( 'keydown', ( event ) => {
		if ( event.key === 'Escape' ) {
			onClose();
		}
	}, { signal: controller.signal } );
	return () => controller.abort();
}, [ onClose ] );

With StrictMode at the root of your app, React runs an effect’s setup and cleanup one extra time in development whenever a component mounts. Without the cleanup above, a single open under StrictMode leaves 2 listeners.

In Vue, the listener goes in onMounted(). You abort it in onUnmounted().

FilePreview.vue
<!-- FilePreview.vue -->
<script setup>
const emit = defineEmits( [ 'close' ] );
const controller = new AbortController();

function onKeydown( event ) {
	if ( event.key === 'Escape' ) {
		emit( 'close' );
	}
}

onMounted( () => window.addEventListener( 'keydown', onKeydown, { signal: controller.signal } ) );
onUnmounted( () => controller.abort() );
</script>

Vue stops the watchers and computed values you create during setup by itself. But a watcher you create later in a callback, like one inside setTimeout(), keeps running once the component unmounts.

Inside <KeepAlive>, a component you close gets deactivated rather than unmounted. That means onUnmounted() doesn’t run, leaving the window listener firing.

That case needs the cleanup in onDeactivated(), a hook Vue only runs inside <KeepAlive>. There, Vue calls onActivated() together with onMounted() on the first mount, and again whenever the cached component comes back.

An aborted controller can’t be reused, because addEventListener() adds nothing for an already-aborted signal. So a component coming back from the cache needs a new controller.

Both hooks call the start() function below for that. It aborts the previous controller and creates the next one. On the first mount, where both hooks run, the second call just replaces what the first one set up. Outside <KeepAlive>, onActivated() never runs.

FilePreview.vue
// FilePreview.vue, inside <script setup>
let controller;

function start() {
	controller?.abort();
	controller = new AbortController();
	window.addEventListener( 'keydown', onKeydown, { signal: controller.signal } );
}

onMounted( start );
onActivated( start );
onUnmounted( () => controller.abort() );
onDeactivated( () => controller.abort() );

For a custom element, listeners on the element itself go in the constructor, where the HTML spec suggests setting up event listeners.

Frameworks move DOM with insertBefore() as well, which means a custom element inside one gets the pair on every move. They differ in what they do with a component that moves, and with one they hide but keep.

Table What each framework does when a component moves or stays hidden.
Built withMoved to another parentKept but hidden
AngularViewContainerRef.detach() and insert() keep the instance with no destroy callbacks, and its DOM nodes are removed and inserted againA view taken out with detach() keeps its listeners and timers running until it’s destroyed
ReactUnmounted and mounted again, so the cleanup runs and then the setup<Activity mode="hidden"> keeps the DOM and runs the effect cleanups
VueUnmounted and mounted again, and <Teleport> moves it without unmounting<KeepAlive> runs onDeactivated(), not onUnmounted()
Custom elementdisconnectedCallback(), then connectedCallback(), or only connectedMoveCallback() under moveBefore() when the class defines itNothing is called
Sources: Angular’s ViewContainerRef docs, React’s pages on preserving state and <Activity>, Vue’s <KeepAlive> and <Teleport> guides, and the HTML spec’s section on custom element state when moved. The Angular row’s DOM removal and re-insertion comes from Angular’s renderer rather than its docs.

Want more of these in your Google results?