Course contentsShow
← Web Development
Lesson 2450 of 2,98244. Web ComponentsFree lesson

disconnectedCallback: Element Removal

Cleaning up event listeners, timers, and resources when your custom element is removed from the DOM.

disconnectedCallback: Element Removal

What you'll learn: How to properly clean up resources when your custom element is removed from the DOM to prevent memory leaks and unwanted behavior.

Why Cleanup Matters

When a custom element is removed from the DOM, any event listeners, timers, or other resources it set up don't automatically disappear. They linger in memory like lights left on in an empty room—wasting resources and potentially causing errors when they try to interact with an element that no longer exists.

The disconnectedCallback Lifecycle Hook

The disconnectedCallback() method is your custom element's chance to say goodbye gracefully. It runs automatically whenever your element is removed from the document—whether through remove(), innerHTML = '', or any other DOM manipulation.

Here's where you should clean up:

class MyCounter extends HTMLElement {
  connectedCallback() {
    this.intervalId = setInterval(() => {
      console.log('Tick');
    }, 1000);
    
    this.handleClick = () => console.log('Clicked!');
    this.addEventListener('click', this.handleClick);
  }
  
  disconnectedCallback() {
    // Stop the timer
    clearInterval(this.intervalId);
    
    // Remove event listener
    this.removeEventListener('click', this.handleClick);
    
    // Clean up any other resources
    console.log('Counter element cleaned up');
  }
}

customElements.define('my-counter', MyCounter);

What to Clean Up

Common cleanup tasks include:

  • Timers: clearInterval() and clearTimeout()
  • Event listeners: removeEventListener() for anything added
  • Network requests: Cancel pending fetch operations
  • Subscriptions: Unsubscribe from external data sources

Key Takeaway: Always implement disconnectedCallback() to clean up timers, event listeners, and other resources created in connectedCallback(), preventing memory leaks and ensuring your custom elements are good DOM citizens.