Component Lifecycle
📅
Component Lifecycle
Core Lifecycle Methods
connectedCallback()
Called when element is added to DOM:
class LifecycleComponent extends HTMLElement {
connectedCallback() {
console.log('Element added to DOM!');
this.innerHTML = '<p>Component initialized</p>';
this.addEventListener('click', this.handleClick);
}
handleClick() {
console.log('Component clicked');
}
}
disconnectedCallback()
Called when element is removed from DOM:
disconnectedCallback() {
console.log('Element removed from DOM!');
this.removeEventListener('click', this.handleClick);
// Cleanup timers, subscriptions, connections
}
attributeChangedCallback()
Reacts to attribute changes:
static get observedAttributes() {
return ['name', 'age', 'status']; // Watched attributes
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(`Attribute ${name} changed: ${oldValue} → ${newValue}`);
if (name === 'name') {
this.updateName(newValue);
}
}
Complete Component Example
class UserProfile extends HTMLElement {
static get observedAttributes() {
return ['name', 'avatar'];
}
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
this.render();
this.setupEventListeners();
}
disconnectedCallback() {
this.cleanupEventListeners();
}
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue !== newValue) {
this.render();
}
}
render() {
this.shadowRoot.innerHTML = `
<div class="profile">
<img src="${this.getAttribute('avatar') || 'default.jpg'}">
<h3>${this.getAttribute('name') || 'No name'}</h3>
</div>
`;
}
setupEventListeners() {
this.clickHandler = this.handleClick.bind(this);
this.shadowRoot.addEventListener('click', this.clickHandler);
}
cleanupEventListeners() {
this.shadowRoot.removeEventListener('click', this.clickHandler);
}
handleClick() {
this.dispatchEvent(new CustomEvent('profile-click', {
bubbles: true,
detail: { userId: this.getAttribute('id') }
}));
}
}
customElements.define('user-profile', UserProfile);
Important Notes
Execution Order
constructor()— instance creationattributeChangedCallback()— if attributes present on creationconnectedCallback()— when inserted into DOM
Behavior Details
connectedCallbackcan be called multiple times if element is moveddisconnectedCallbackis not called on page closeattributeChangedCallbackonly works for attributes inobservedAttributes
Best Practices
- Don't call
connectedCallbackin constructor — element not in DOM yet - Always cleanup resources in
disconnectedCallback - Optimize rendering in
attributeChangedCallback - Use
observedAttributesto track needed attributes