Skip to main content Accessibility Feedback

You're (probably) using connectedCallback() wrong in your Web Component

If you’ve been following along with my series on Web Components, you’ve likely noticed that I tend to add my event listeners in the connectedCallback() method, and remove them in the disconnectedCallback() method.

customElements.define('count-up', class extends HTMLElement {

	// Instantiate the component
	constructor () {
		super();
		this.count = 0;
	}

	// Create the click handler
	handleEvent (event) {
		this.count++;
	} 

	// Start listening
	connectedCallback () {
		this.addEventListener('click', this);
	}

	// Stop listening
	disconnectedCallback () {
		this.removeEventListener('click', this);
	}

});

But in the article “You’re (probably) using connectedCallback wrong,” Hawk Ticehurst argues that event listener instantiations should probably just got in the constructor().

The thinking is that you generally only need or want to add them once, and if the element gets removed from the DOM, the browser will garbage collect the event listeners anyways.

Where I think this gets tricky is if you want to attach listeners to elements inside your Web Component, and when you don’t generate them until later in the process.

But I also think that’s an exception rather than a rule.