Concept Explanation
A Web Component has a life story, and the browser narrates it by calling four special methods on your class:
| Hook | When it fires | Use it for |
|---|---|---|
constructor() | The element object is created | Setting default fields, attaching Shadow DOM |
connectedCallback() | It gets inserted into the page | Rendering, fetching data, adding listeners |
disconnectedCallback() | It gets removed from the page | Cleanup: timers, listeners, subscriptions |
attributeChangedCallback() | A watched attribute changes | Re-rendering the affected part |
Think of it like renting an apartment. The constructor is signing the lease, connectedCallback is moving your furniture in, attributeChangedCallback is redecorating, and disconnectedCallback is handing back the keys and turning off the utilities.
That last one is the hook beginners forget, and it is the one that causes the leaks.
Syntax or Core Structure
class TimerElement extends HTMLElement {
connectedCallback() {
this.timer = setInterval(() => {
this.innerText = new Date().toLocaleTimeString();
}, 1000);
}
disconnectedCallback() {
clearInterval(this.timer); // Crucial for performance!
console.log("Timer removed from page.");
}
}
customElements.define('time-now', TimerElement);
Watching Attributes
You must declare which attributes you care about. If it is not in observedAttributes, the hook never fires.
class GreetTag extends HTMLElement {
static get observedAttributes() {
return ['name']; // only 'name' is watched
}
attributeChangedCallback(attr, oldValue, newValue) {
if (oldValue === newValue) return; // ignore no-op writes
this.render();
}
connectedCallback() { this.render(); }
render() {
const who = this.getAttribute('name') || 'stranger';
this.textContent = 'Hello, ' + who + '!';
}
}
customElements.define('greet-tag', GreetTag);
Real World Example
A live stock ticker widget. The component opens a WebSocket in connectedCallback and closes it in disconnectedCallback. A user opens ten tabs of your dashboard and closes nine of them. Without the disconnect cleanup, those nine sockets stay open, the server keeps pushing data to invisible elements, and the laptop fan spins up. With it, the connection dies the moment the element leaves the page.
Common Mistakes
- Rendering in the constructor. At constructor time the element has no attributes and no children yet, so
this.getAttribute('name')returnsnull. Render inconnectedCallbackinstead. - Touching the DOM in the constructor. The spec forbids adding children or setting attributes there. Chrome will throw.
- Forgetting
observedAttributes. YourattributeChangedCallbacksilently never runs and you spend an hour blaming the browser. - Assuming connect happens once. Moving an element with
appendChilddisconnects then reconnects it, so both hooks fire again. Make them idempotent.
Best Practices
- Every subscription created in
connectedCallbackneeds a matching teardown indisconnectedCallback. Write them as a pair, in the same commit. - Keep a single
render()method and call it from the hooks, rather than duplicating DOM-building logic. - Bail out early when
oldValue === newValueso a redundantsetAttributedoes not trigger a repaint. - Store timer and listener handles on
thisso cleanup can actually reach them.
Practice Exercises
- The Cleanup Crew: Write a component that starts a
setTimeoutin its connected callback and clears it in its disconnected callback. - The Fetcher: Create a component
<user-info id="1">that fetches user data from an API as soon as it is added to the page. - The Logger: Add logs to every lifecycle hook of a component and move it around the DOM using
appendChildto see which hooks trigger.