Sub topic 9
Cleaning up event listeners and timers
This chapter covers how to release the things a component sets up when it is inserted. It assumes you know the order of the lifecycle hooks and that connectedCallback() and disconnectedCallback() run when a component enters and leaves the DOM. It also assumes you are comfortable with basic JavaScript classes, DOM events, and setTimeout/setInterval.
Why cleanup matters
JavaScript frees an object only when nothing refers to it any more. A component that you remove from the page is not freed if something global still points at it. A window listener, a running interval, or an open subscription each hold a reference to your callback. The callback holds this, and this holds the whole component and everything it references.
Leaving these in place causes three kinds of problems:
- Memory growth. Each time the component is created and removed, another copy of the listener or timer stays alive.
- Wasted work. A removed component keeps running handlers, recalculating values, and possibly calling the server.
- Wrong behavior. A stale handler can dispatch events, update shared state, or show a toast for a component the user can no longer see.
The fix follows one rule: whatever connectedCallback() acquires, disconnectedCallback() releases.
What needs cleanup and what does not
Not every listener needs removing. The test is whether the thing you registered with outlives your component.
| Resource | Acquire | Release | Needs manual cleanup? |
|---|---|---|---|
| Listener on `window` or `document` | `addEventListener` | `removeEventListener` | Yes |
| Interval | `setInterval` | `clearInterval` | Yes |
| Pending timeout | `setTimeout` | `clearTimeout` | Yes, if it can fire after removal |
| Observer (`ResizeObserver`, `IntersectionObserver`, `MutationObserver`) | `observe` | `disconnect` | Yes |
| In-flight `fetch` | `fetch` with an `AbortSignal` | `abort()` | Usually yes |
| Message channel or streaming subscription | `subscribe` | `unsubscribe` | Yes |
| Listener on an element in your own template | `addEventListener` | none | No |
| `onclick={handler}` in the template | template binding | none | No |
Elements in your own template are discarded together with the component, so listeners attached to them go away with them. Template bindings such as onclick={handler} are managed by the framework. Resources that live outside your template need manual cleanup. That means the window, the document, the global timer queue, and any shared service.
Removing event listeners
removeEventListener only removes a listener if you pass the same function reference, the same event type, and the same capture setting that you passed to addEventListener. Two functions with identical bodies are different references.
The following component never removes its listener, even though it looks like it does:
import { LightningElement } from 'lwc';
export default class BrokenResize extends LightningElement {
width;
connectedCallback() {
window.addEventListener('resize', () => {
this.width = window.innerWidth;
});
}
disconnectedCallback() {
// This arrow function is a new object, so nothing is removed.
window.removeEventListener('resize', () => {
this.width = window.innerWidth;
});
}
}The fix is to store the handler once and use that reference in both places. A class field holding an arrow function works well, because the arrow function keeps this bound to the component:
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);
}
}If you prefer a regular method, this.handleResize.bind(this) creates a new function on every call. Bind once, store the result in a field, and use that field for both calls.
import { LightningElement } from 'lwc';
export default class BoundHandler extends LightningElement {
boundHandler;
constructor() {
super();
this.boundHandler = this.handleKey.bind(this);
}
handleKey(event) {
console.log('Key pressed:', event.key);
}
connectedCallback() {
document.addEventListener('keydown', this.boundHandler);
}
disconnectedCallback() {
document.removeEventListener('keydown', this.boundHandler);
}
}If you add a listener with options, such as { capture: true }, pass the same capture value when removing it. Other options such as passive and once do not affect matching.
Clearing timers
setInterval keeps calling your function until you call clearInterval with the id it returned. Store the id in a field so disconnectedCallback() can reach it.
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;
}
}The matching template is:
<template>
<p>The time is {now}</p>
</template>Without the clearInterval call, each removal and re-insertion of Clock would leave one more interval running. After a few toggles the page would run several copies, all updating fields on components that are no longer displayed.
Timeouts
A setTimeout that has not fired yet is also a pending reference. It is most often a problem in debounce logic, where you wait for the user to stop typing before acting:
import { LightningElement } from 'lwc';
export default class SearchBox extends LightningElement {
query = '';
timeoutId;
handleInput(event) {
const value = event.target.value;
clearTimeout(this.timeoutId);
this.timeoutId = setTimeout(() => {
this.query = value;
this.dispatchEvent(
new CustomEvent('search', { detail: { query: value } })
);
}, 300);
}
disconnectedCallback() {
clearTimeout(this.timeoutId);
this.timeoutId = undefined;
}
}Calling clearTimeout on every keystroke cancels the previous wait. The call in disconnectedCallback() makes sure a user who closes the panel within 300 ms does not trigger a search event from a component that has gone.
clearTimeout and clearInterval are safe to call with undefined or with an id that has already fired, so you do not need to check first.
Observers and other resources
Observers follow the same pattern, with one extra detail. The element you want to observe usually lives in your template. It does not exist during connectedCallback(), so you create the observer in renderedCallback() and disconnect it in disconnectedCallback().
import { LightningElement } from 'lwc';
export default class ResizeAware extends LightningElement {
observer;
boxWidth = 0;
renderedCallback() {
if (this.observer) {
return;
}
const box = this.template.querySelector('.box');
if (!box) {
return;
}
this.observer = new ResizeObserver((entries) => {
this.boxWidth = Math.round(entries[0].contentRect.width);
});
this.observer.observe(box);
}
disconnectedCallback() {
if (this.observer) {
this.observer.disconnect();
this.observer = undefined;
}
}
}The check if (this.observer) replaces the hasRendered flag from the earlier renderedCallback() chapter. It also stays correct after a re-insertion. disconnectedCallback() resets observer to undefined, so the next render creates a new observer for the new DOM. A boolean flag that is never reset would skip that step.
For network requests, an AbortController cancels a request that is still in flight:
import { LightningElement } from 'lwc';
export default class Loader extends LightningElement {
controller;
data;
connectedCallback() {
this.controller = new AbortController();
fetch('/api/items', { signal: this.controller.signal })
.then((response) => response.json())
.then((json) => {
this.data = json;
})
.catch((error) => {
if (error.name !== 'AbortError') {
console.error(error);
}
});
}
disconnectedCallback() {
this.controller.abort();
}
}The AbortError check keeps a deliberate cancellation from being reported as a failure. In a Salesforce org, data access normally goes through Apex or the wire service, and this example only shows the cancellation pattern. For Lightning Message Service, Streaming API, or empApi, store the subscription object that subscribe returns and pass it to the matching unsubscribe function in disconnectedCallback().
The acquire and release timeline
The diagram shows what the browser delivers to the component over its life when cleanup is done properly.
A reusable structure
When a component owns several resources, keep the acquire and release code symmetric so a missing release is easy to spot. Two habits help:
- Give every resource a named field (
intervalId,observer,handleResize,subscription). - Write
disconnectedCallback()as a list that mirrorsconnectedCallback(), one release per acquire, in reverse order.
import { LightningElement } from 'lwc';
export default class Dashboard extends LightningElement {
intervalId;
isOnline = true;
handleOnline = () => {
this.isOnline = true;
};
handleOffline = () => {
this.isOnline = false;
};
connectedCallback() {
window.addEventListener('online', this.handleOnline);
window.addEventListener('offline', this.handleOffline);
this.intervalId = setInterval(() => this.refresh(), 30000);
}
disconnectedCallback() {
clearInterval(this.intervalId);
this.intervalId = undefined;
window.removeEventListener('offline', this.handleOffline);
window.removeEventListener('online', this.handleOnline);
}
refresh() {
// Reload data here.
}
}Common mistakes
- Removing a different function. Passing a new arrow function or a fresh
.bind()result toremoveEventListenersilently does nothing. Store one reference. - Acquiring in the constructor. The constructor runs once, but the component can be connected many times. After the first removal, a constructor-registered resource would be released and never re-acquired.
- Forgetting the id. Writing
setInterval(...)without saving the return value leaves no way to clear it. - Releasing only on the happy path. If
connectedCallback()can throw part-way through,disconnectedCallback()may run for a half-initialized component. Make each release tolerate a missing resource, for example withif (this.observer). Theclear*functions already tolerateundefined. - Assuming a stale timer is harmless. A callback that fires after removal can still dispatch events or call services. Clear the timer instead of guarding inside the callback.
- Leaving a stale reference. After releasing, set the field to
undefined. This lets the nextconnectedCallback()orrenderedCallback()tell that it needs a new resource.
Exercises
Exercise
A component calls window.addEventListener('scroll', this.handleScroll.bind(this)) in connectedCallback and window.removeEventListener('scroll', this.handleScroll.bind(this)) in disconnectedCallback. The listener keeps firing after the component is removed. Why, and how do you fix it?
Show answer
Each call to bind returns a new function object, so removeEventListener receives a reference that was never registered and removes nothing. Create the handler once, either as an arrow-function class field (handleScroll = () => { ... }) or as a bound function stored in a field, and pass that same reference to both addEventListener and removeEventListener.
Exercise
A component starts a setInterval in its constructor and clears it in disconnectedCallback. The parent hides the component with lwc:if and later shows it again. What happens after the second insertion, and where should the interval be started instead?
Show answer
After the first removal, disconnectedCallback clears the interval. The constructor does not run again when the same instance is re-inserted, so nothing starts a new interval and the component stops updating. Start the interval in connectedCallback, which runs on every insertion, and keep clearing it in disconnectedCallback.
Exercise
You create a ResizeObserver in renderedCallback, guarded by a boolean field hasRendered that is never reset. The component is removed and then re-inserted. What is the problem, and what guard is safer?
Show answer
disconnectedCallback disconnects the observer, but hasRendered stays true, so after re-insertion the guard skips creating a new observer and the new DOM is never observed. Guard on the observer itself instead (if (this.observer) return;) and set this.observer = undefined in disconnectedCallback after calling disconnect().