Custom Elements Lifecycle (connectedCallback)0%

Custom Elements Lifecycle (connectedCallback)

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

Custom Elements Lifecycle (connectedCallback & More)

Custom Elements are the core pillar of the W3C Web Components standard, enabling developers to define fully autonomous, reusable HTML tags with encapsulated behavior and state. Understanding the Custom Elements Lifecycle is essential for building framework-agnostic component libraries.


1. Defining a Custom Element

Custom elements extend HTMLElement and are registered with the browser's customElements registry:

JavaScript
class UserAvatar extends HTMLElement {
constructor() {
super(); // Mandatory call to super()!
console.log('1. Constructor: Element instantiated.');
}
}
 
// Custom element names MUST contain a hyphen (-) to avoid collisions with HTML tags!
customElements.define('user-avatar', UserAvatar);
HTML
<!-- Now valid HTML! -->
<user-avatar></user-avatar>

2. The 4 Lifecycle Callbacks

Output
┌─────────────────────────────────────────────────────────────┐
│ CUSTOM ELEMENT LIFECYCLE │
├──────────────────────────────┬──────────────────────────────┤
│ connectedCallback() │ Element inserted into DOM │
│ │ (Setup listeners, fetch data)│
├──────────────────────────────┼──────────────────────────────┤
│ disconnectedCallback() │ Element removed from DOM │
│ │ (Cleanup timers, listeners) │
├──────────────────────────────┼──────────────────────────────┤
│ attributeChangedCallback() │ Observed attribute updated │
├──────────────────────────────┼──────────────────────────────┤
│ adoptedCallback() │ Element moved to new document│
└──────────────────────────────┴──────────────────────────────┘

3. Observing Attribute Changes

To listen to attribute modifications via attributeChangedCallback(), you must declare a static getter named observedAttributes:

JavaScript
class NotificationBadge extends HTMLElement {
static get observedAttributes() {
return ['count', 'theme']; // List attributes to monitor
}
 
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
 
connectedCallback() {
this.render();
}
 
// Triggered whenever 'count' or 'theme' is added, updated, or removed
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue !== newValue) {
console.log(`Attribute "${name}" changed from "${oldValue}" to "${newValue}"`);
this.render();
}
}
 
disconnectedCallback() {
console.log('Badge destroyed. Performing cleanup.');
}
 
render() {
const count = this.getAttribute('count') || '0';
const theme = this.getAttribute('theme') || 'primary';
 
this.shadowRoot.innerHTML = `
<style>
.badge {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.25rem 0.5rem;
border-radius: 9999px;
font-weight: bold;
font-size: 0.75rem;
color: white;
}
.primary { background: #3b82f6; }
.danger { background: #ef4444; }
</style>
<span class="badge ${theme}">${count}</span>
`;
}
}
 
customElements.define('notification-badge', NotificationBadge);

Live Mutation in Action:

JavaScript
const badge = document.querySelector('notification-badge');
badge.setAttribute('count', '5'); // attributeChangedCallback fires -> auto re-renders!
badge.setAttribute('theme', 'danger');

4. Autonomous vs. Customized Built-in Elements

  1. 1
    Autonomous Custom Element: Extends HTMLElement. Used as <my-tag>.
  2. 2
    Customized Built-in Element: Extends a specific tag (e.g. HTMLButtonElement). Used with the is attribute:
JavaScript
class ConfirmButton extends HTMLButtonElement { ... }
customElements.define('confirm-button', ConfirmButton, { extends: 'button' });
HTML
<button is="confirm-button">Delete Account</button>

Interactive Quiz

Practice Quiz

Question 1
What naming convention is strictly required for Custom Element tag names?
Question 2
Which lifecycle callback fires when a Custom Element is attached to the active DOM?
Question 3
What must be defined on the class for attributeChangedCallback() to receive notifications when an attribute changes?
Question 4
Which lifecycle hook should be used to clear intervals and remove window event listeners?
Question 5
What base class must an autonomous Custom Element inherit from?
Next Lesson

Virtual DOM Concepts & Reconciliation

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext