Sub topic 8
disconnectedCallback(): running code when the component is removed
This chapter assumes you know JavaScript classes and ES modules, can build a Lightning Web Component (LWC) with an HTML template and a JavaScript class, and understand basic DOM events. You should also have read the chapter on connectedCallback(), because disconnectedCallback() mirrors it.
What disconnectedCallback() does
disconnectedCallback() is a lifecycle hook that the framework calls when a component is removed from the DOM. It is the counterpart of connectedCallback(). Whatever you set up when the component was inserted, you undo here.
The hook runs in these cases:
- A parent stops rendering the component, for example because an
if:trueorlwc:ifcondition becomes false. - A parent re-renders a list and the item is no longer in it.
- The parent itself is removed, so all its children are removed with it.
The hook takes no arguments and returns nothing. When it runs, the component instance still exists and you can read its fields. The component is no longer attached to the DOM, so do not try to work with the rendered elements.
Why cleanup matters
Removing a component from the page does not remove everything it registered. Some things live outside the component and keep references to it:
- Listeners added to
window,document, or other elements outside the component's template. - Timers created with
setIntervalorsetTimeout. - Subscriptions to message channels or other event sources.
If you leave these in place, they keep calling your component's functions after it is gone. The component also cannot be garbage collected, because the listener still points to it. This is a memory leak, and it grows each time the component is inserted and removed.
Listeners that you attach in the template, such as onclick={handleClick}, belong to the component's own elements. The framework cleans those up for you. You only need to handle what you registered yourself on something that outlives the component.
A worked example: removing a window listener
This component tracks the browser width. It registers a resize listener in connectedCallback() and removes it in disconnectedCallback().
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);
}
}The handler is stored in a class field, handleResize. This matters because removeEventListener only removes a listener when you pass the same function reference that you passed to addEventListener. The arrow function field gives you one stable reference for the whole life of the instance.
Cleaning up timers
Timers follow the same pattern. Keep the timer id in a field, then clear it on removal.
import { LightningElement } from 'lwc';
export default class Clock extends LightningElement {
now = new Date().toLocaleTimeString();
intervalId;
connectedCallback() {
this.intervalId = setInterval(() => {
this.now = new Date().toLocaleTimeString();
}, 1000);
}
disconnectedCallback() {
clearInterval(this.intervalId);
this.intervalId = undefined;
}
}Without clearInterval, the callback would keep running every second and keep updating a component nobody can see.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Passing a new function to `removeEventListener` | The listener is not removed, because the reference differs. | Store the handler in a field and reuse it. |
| Forgetting to clear a timer | The callback keeps firing after removal. | Call `clearInterval` or `clearTimeout`. |
| Adding listeners in `renderedCallback()` without a guard | Duplicate listeners pile up, and one cleanup call removes only one. | Register in `connectedCallback()`. |
| Reading the rendered DOM in `disconnectedCallback()` | The elements may already be detached. | Read what you need earlier and keep it in a field. |
Checking your work
To confirm that a cleanup works, add a temporary console.log inside the handler. Remove the component by toggling the condition that renders it, then trigger the event again. If the message still prints, the listener is still registered. Check that you passed the same function reference to both addEventListener and removeEventListener.
Exercise
A component calls window.addEventListener('scroll', () => this.update()) in connectedCallback(). In disconnectedCallback(), it calls window.removeEventListener('scroll', () => this.update()). Why does the leak remain, and how do you fix it?
Show answer
Each arrow function expression creates a new function object, so the one passed to removeEventListener is not the one that was registered. Nothing is removed. Store the handler in a class field, such as handleScroll = () => this.update();, pass this.handleScroll to both addEventListener and removeEventListener.
Exercise
A component starts a setInterval in connectedCallback() and saves the id in this.intervalId. What should disconnectedCallback() do, and what happens if it does nothing?
Show answer
It should call clearInterval(this.intervalId). If it does nothing, the interval keeps running after the component is removed. The callback keeps a reference to the component, so it cannot be garbage collected, and it keeps doing work that no one sees.