Sub topic 3
disconnectedCallback(): Running Code When a Component Is Removed
Assume you know JavaScript classes, LWC templates, reactive properties, and DOM events. This chapter focuses on cleanup and errors after a component has been created.
disconnectedCallback()
disconnectedCallback() runs when an LWC is removed from the document. It is the right place to release resources created in connectedCallback(), such as event listeners, timers, subscriptions, or observers.
A component can be removed and inserted again, so the hook may run more than once.
Cleaning Up Event Listeners and Timers
Use the same function reference when removing an event listener. A class field arrow function provides a stable reference.
import { LightningElement } from 'lwc';
export default class WindowSize extends LightningElement {
width;
timerId;
handleResize = () => {
this.width = window.innerWidth;
};
connectedCallback() {
this.width = window.innerWidth;
window.addEventListener('resize', this.handleResize);
this.timerId = window.setInterval(() => {
console.log('Checking window size');
}, 10000);
}
disconnectedCallback() {
window.removeEventListener('resize', this.handleResize);
window.clearInterval(this.timerId);
this.timerId = undefined;
}
}errorCallback(): Catching Errors from Child Components
errorCallback(error, stack) runs on a parent when a descendant component throws an error during rendering or a lifecycle hook. The parent can save the error and display a fallback view.
import { LightningElement } from 'lwc';
export default class ErrorBoundary extends LightningElement {
error;
errorCallback(error, stack) {
this.error = `${error.message}\n${stack}`;
}
}This boundary handles errors from child components, not errors thrown by the boundary itself.
Common Pitfalls and Best Practices
- Do not create duplicate listeners each time
connectedCallback()runs. - Do not pass a new anonymous function to
removeEventListener(). - Do not access rendered elements in
disconnectedCallback(); they are no longer available. - Keep
renderedCallback()guarded when it performs one-time work. - Avoid changing reactive state from
renderedCallback()unless the change is controlled, or you may cause a render loop. - Clean up subscriptions, observers, timers, and listeners together.
Exercise
Why must handleResize use the same function reference in both listener calls?
Show answer
removeEventListener() only removes the listener when it receives the exact function reference used by addEventListener().