Sub topic 9
Cleaning up event listeners and timers
This chapter assumes you know JavaScript classes and ES modules, can build a Lightning Web Component with a template and a class, and understand reactive properties and basic DOM events. It also assumes you have read the earlier chapters on connectedCallback() and disconnectedCallback().
Why cleanup matters
A component can be inserted and removed many times. A tab panel, a modal, or a list row may be created and destroyed repeatedly during one session. Anything the component registers outside its own template stays alive after removal unless you release it.
These resources are the usual culprits:
- Listeners on
window,document, or other elements the component does not own. - Timers from
setIntervalandsetTimeout. - Subscriptions to message channels or other event sources.
Each one holds a reference to your component's callback. The browser's garbage collector cannot free the component while that reference exists. The callback keeps running too, and it may update a component that is no longer on the page.
Listeners declared in the template, such as onclick={handleClick}, belong to the component's own DOM. The engine removes them with the component, so you do not clean those up.
The pairing rule
Set up in connectedCallback(). Tear down in disconnectedCallback(). Every addEventListener needs a matching removeEventListener, and every setInterval needs a clearInterval.
Removing a listener
removeEventListener only works if you pass the same function reference that you passed to addEventListener. An arrow function written inline creates a new function each time, so it cannot be removed.
This version cannot be cleaned up:
connectedCallback() {
window.addEventListener('resize', () => this.update());
}Store the handler once, as a class field, and reuse it:
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 arrow function field keeps this bound to the component, and it is the same reference in both hooks.
Cleaning up a timer
Save the timer ID returned by setInterval and clear it on disconnect. Without that, the interval keeps firing after the component is gone.
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;
}
}Use clearTimeout for setTimeout in the same way. A one-shot timeout that is still pending when the component is removed will run its callback later, so clear it too.
Connected more than once
A component can be disconnected and then connected again. This happens when a parent moves it in the DOM, or when it is removed and re-inserted. The same instance runs connectedCallback() again. Your setup code must therefore be safe to repeat, and your teardown must leave the instance ready for another setup.
connectedCallback() {
if (this.intervalId === undefined) {
this.intervalId = setInterval(this.tick, 1000);
}
}Resetting intervalId to undefined in disconnectedCallback(), as in the Clock example, makes this guard work.
Quick checklist
| Registered with | Released with | Where to store the reference |
|---|---|---|
| `addEventListener` | `removeEventListener` | A class field holding the handler |
| `setInterval` | `clearInterval` | A field holding the ID |
| `setTimeout` | `clearTimeout` | A field holding the ID |
| A message channel subscription | The matching unsubscribe call | A field holding the subscription |
Exercise
A component calls window.addEventListener('scroll', () => this.track()) in connectedCallback() and tries window.removeEventListener('scroll', () => this.track()) in disconnectedCallback(). Why does the listener keep running after removal, and how do you fix it?
Show answer
The two arrow functions are different function objects, so removeEventListener finds nothing to remove. Define the handler once as a class field, for example handleScroll = () => { this.track(); };, then pass this.handleScroll to both addEventListener and removeEventListener.
Exercise
Why should disconnectedCallback() set a stored interval ID back to undefined after calling clearInterval?
Show answer
The same instance can be connected again, and connectedCallback() runs again. Resetting the ID lets a guard such as if (this.intervalId === undefined) decide correctly whether a new interval is needed, and it avoids holding a stale ID.