Sub topic 8
disconnectedCallback(): running code when the component is removed
This chapter assumes you can write an LWC class with connectedCallback(), you know that this.template is the component's shadow root, and you have used addEventListener in plain JavaScript. The earlier chapters on connectedCallback() and renderedCallback() cover the setup half of the lifecycle. This chapter covers the teardown half.
What disconnectedCallback() is for
disconnectedCallback() is a lifecycle hook that the engine calls when the component is removed from the DOM. Use it to undo whatever connectedCallback() or later code set up outside the component: global event listeners, timers, subscriptions to external services, and references that would otherwise keep the component alive.
The hook takes no arguments and its return value is ignored. You define it as a method on the class:
import { LightningElement } from 'lwc';
export default class Example extends LightningElement {
disconnectedCallback() {
// release anything that lives outside this component
}
}The reason it matters is garbage collection. A component is normally collected once nothing references it. A listener registered on window holds a reference to the handler, and the handler (through this) holds a reference to the component. The browser never collects the component, and the handler keeps running against a component that is no longer on the page.
When it runs
The engine calls disconnectedCallback() each time the component leaves the DOM. Common causes are:
- A parent template stops rendering the child, for example because a conditional directive such as
lwc:ifbecame false. - A parent re-renders a list and an item is no longer in it.
- The component's ancestor is removed, for instance when the user navigates to another page in the app.
- Code removes or moves the element with DOM APIs such as
removeChild().
Moving an element counts as a removal followed by an insertion. The engine calls disconnectedCallback() and then connectedCallback() on the same instance. The constructor does not run again, because the instance is the same object.
The block above is a placeholder only if rendered empty, so here is the actual diagram.
Because a component can be connected more than once, the rule is that every setup step in connectedCallback() needs a matching teardown step in disconnectedCallback(). If you add a listener on every connection and never remove it, a moved component ends up with two listeners.
What you can and cannot rely on
When disconnectedCallback() runs, the instance is still intact. You can read and write this fields and call your own methods. The component is no longer in the document, though. Two consequences follow.
- Do not query for layout or measure elements. The component's DOM is detached, so sizes and positions are not meaningful.
- Do not start new work. Changing a field will not usefully update the screen, and starting a fetch or a timer here creates the very leak you are trying to prevent.
The hook is also not a reliable place to save data. If the user closes the browser tab or the page reloads, the browser tears down the whole document and component callbacks may not run. Persist important data when the user acts, not on removal.
| Question | Answer |
|---|---|
| Does it run on every removal? | Yes, each time the component leaves the DOM. |
| Does the constructor run again after re-insertion? | No. Only `connectedCallback()` runs again. |
| Can I rely on it when the tab closes? | No. Treat it as cleanup, not as a save point. |
| Is `this` available? | Yes. Fields and methods still work. |
| Is the DOM measurable? | No. The component is detached. |
Order across parent and child
Removal is the reverse concern of insertion, but the order is not a mirror image of connection. When a parent is removed, the engine calls the parent's disconnectedCallback() first and then the callbacks of the children inside it. Do not write code that depends on a child having been cleaned up before its parent, or the reverse between siblings. Each component should clean up only what it created itself.
This also means a child should never assume its parent is still around in disconnectedCallback(). If the child registered a listener on a service, the child unregisters it. It should not ask the parent to do so.
Example: removing a global listener
The WindowSize component registers a resize listener on window. The handler is a class field holding an arrow function. That detail matters, as the next section explains.
import { LightningElement } from 'lwc';
export default class WindowSize extends LightningElement {
width;
handleResize = () => {
this.width = window.innerWidth;
};
connectedCallback() {
this.width = window.innerWidth;
window.addEventListener('resize', this.handleResize);
}
disconnectedCallback() {
window.removeEventListener('resize', this.handleResize);
}
}removeEventListener() only removes a listener when you pass the same function reference, the same event type, and the same capture setting that you passed to addEventListener(). This is why the handler is stored in a field.
// Bug: each arrow function is a new object, so nothing is removed.
connectedCallback() {
window.addEventListener('resize', () => this.update());
}
disconnectedCallback() {
window.removeEventListener('resize', () => this.update());
}The two arrow functions above are different objects. The removal silently does nothing and the original listener keeps running. A bound method has the same problem if you call .bind(this) in both places, since each call returns a new function. Create the bound or arrow function once, store it on the instance, and use that stored reference in both calls.
Which listeners need removal
Not every listener needs manual cleanup. The rule depends on what the listener is attached to.
| Listener target | Cleanup needed? | Why |
|---|---|---|
| `this.template` or an element inside your template | Usually no | These objects belong to the component and are collected with it. |
| `this` (the host element) | Usually no | The host is tied to the component's own lifetime. |
| `window`, `document`, `document.body` | Yes | They outlive the component and hold the handler. |
| An element owned by another component or the page | Yes | Its lifetime is independent of yours. |
If you attach a handler to a long-lived target from inside the component, you need a matching removal.
Example: stopping timers
Timers created with setInterval() or setTimeout() keep running after the component is gone, and they keep the component object alive through the callback. Save the timer ID and clear it.
import { LightningElement } from 'lwc';
export default class Clock extends LightningElement {
time = '';
intervalId;
connectedCallback() {
this.updateTime();
this.intervalId = setInterval(() => this.updateTime(), 1000);
}
disconnectedCallback() {
clearInterval(this.intervalId);
this.intervalId = undefined;
}
updateTime() {
this.time = new Date().toLocaleTimeString();
}
}Setting intervalId back to undefined is optional but useful. It makes the field reflect the real state, so a later connectedCallback() or a guard such as if (this.intervalId) behaves correctly. The same pattern applies to setTimeout() and clearTimeout(). A one-shot timeout that has not fired yet will still fire after removal unless you clear it.
Example: one signal to cancel many listeners
When a component registers several listeners, tracking each handler reference gets tedious. An AbortController lets you cancel them all with one call. You pass its signal to addEventListener() and call abort() on teardown.
import { LightningElement } from 'lwc';
export default class PageWatcher extends LightningElement {
online = true;
visible = true;
controller;
connectedCallback() {
this.controller = new AbortController();
const { signal } = this.controller;
window.addEventListener('online', () => { this.online = true; }, { signal });
window.addEventListener('offline', () => { this.online = false; }, { signal });
document.addEventListener(
'visibilitychange',
() => { this.visible = document.visibilityState === 'visible'; },
{ signal }
);
}
disconnectedCallback() {
this.controller.abort();
this.controller = undefined;
}
}Creating the controller inside connectedCallback() is deliberate. A controller can be aborted only once, so a component that is removed and re-inserted needs a fresh one each time it connects. If you created it in the constructor or as a field initializer, the second connection would pass an already aborted signal, and no listeners would be registered.
Subscriptions and other external resources
Listeners and timers are the common cases. The same pattern covers anything that holds a reference to your component from the outside:
- A subscription to a message channel, a streaming event service, or any publish/subscribe API. Most return a handle or a token. Store it and call the matching unsubscribe function.
- An
IntersectionObserver,ResizeObserver, orMutationObserver. Calldisconnect()on the observer. - A
WebSocketorEventSourcethat you opened. Callclose(). - A polling loop built from chained
setTimeout()calls. Set a flag or clear the pending ID so the next call is not scheduled.
A short observer example shows the shape:
import { LightningElement } from 'lwc';
export default class VisibilityTracker extends LightningElement {
observer;
isVisible = false;
renderedCallback() {
if (this.observer) {
return;
}
const target = this.template.querySelector('.tracked');
if (!target) {
return;
}
this.observer = new IntersectionObserver((entries) => {
this.isVisible = entries[0].isIntersecting;
});
this.observer.observe(target);
}
disconnectedCallback() {
if (this.observer) {
this.observer.disconnect();
this.observer = undefined;
}
}
}This component starts its work in renderedCallback() because it needs a rendered element, and the guard on this.observer keeps it from creating a second observer on later renders. The teardown still lives in disconnectedCallback(). Resource creation can happen in any hook, but release always belongs here.
Writing defensive teardown
A teardown method can run in states you did not plan for, so write it to tolerate them.
- Check that a resource exists before releasing it. A component can be disconnected before
renderedCallback()ever created the observer above. - Reset fields to their empty value after releasing, so a second connection starts clean.
- Release in a way that does not throw. An error in
disconnectedCallback()can interrupt the removal, so do not do risky work there. - Keep it fast and synchronous. Do not wait on a network call before cleaning up.
Common mistakes
- Registering a listener in
connectedCallback()with an inline arrow function, then trying to remove it with a different function. - Creating a timer in
connectedCallback()and forgettingclearInterval(). The visible symptom is console errors or network calls from a component that is not on the page. - Relying on
disconnectedCallback()to save user data. - Assuming the constructor runs again after a move and putting setup there. Setup that must repeat belongs in
connectedCallback(). - Reading layout or querying child components during teardown.
- Removing listeners from
this.templatechildren. This is harmless but unnecessary and adds noise.
Exercise
A component adds a scroll listener to window in connectedCallback() with window.addEventListener('scroll', () => this.track());. Its disconnectedCallback() calls window.removeEventListener('scroll', () => this.track());. After the component is removed from the page, track() still runs on every scroll. Explain why, and show a corrected version of the component.
Show answer
The two arrow functions are different function objects, so removeEventListener() finds no matching listener and does nothing, and it does not throw. The original listener stays on window and keeps the component alive. Store one handler on the instance and use it in both calls:
class ScrollTracker extends LightningElement {
handleScroll = () => {
this.track();
};
connectedCallback() {
window.addEventListener('scroll', this.handleScroll);
}
disconnectedCallback() {
window.removeEventListener('scroll', this.handleScroll);
}
track() {
// react to scrolling
}
}
Exercise
A component creates this.controller = new AbortController() in its constructor, passes this.controller.signal to its listeners in connectedCallback(), and calls this.controller.abort() in disconnectedCallback(). A parent moves the component to another position in the DOM. What goes wrong, and how do you fix it?
Show answer
A move triggers disconnectedCallback() and then connectedCallback() on the same instance, and the constructor does not run again. The controller was already aborted, so the signal passed to the new listeners is already aborted and addEventListener() registers nothing. The component stops responding after the move. Create the AbortController inside connectedCallback() so each connection gets a fresh one.