Lifecycle Hooks: The Birth and Death of a Tag

Lifecycle Hooks: The Birth and Death of a Tag in JavaScript: A Web Component has a life story, and the browser narrates it by calling four special methods on…

Concept Explanation

A Web Component has a life story, and the browser narrates it by calling four special methods on your class:

HookWhen it firesUse it for
constructor()The element object is createdSetting default fields, attaching Shadow DOM
connectedCallback()It gets inserted into the pageRendering, fetching data, adding listeners
disconnectedCallback()It gets removed from the pageCleanup: timers, listeners, subscriptions
attributeChangedCallback()A watched attribute changesRe-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') returns null. Render in connectedCallback instead.
  • Touching the DOM in the constructor. The spec forbids adding children or setting attributes there. Chrome will throw.
  • Forgetting observedAttributes. Your attributeChangedCallback silently never runs and you spend an hour blaming the browser.
  • Assuming connect happens once. Moving an element with appendChild disconnects then reconnects it, so both hooks fire again. Make them idempotent.

Best Practices

  • Every subscription created in connectedCallback needs a matching teardown in disconnectedCallback. 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 === newValue so a redundant setAttribute does not trigger a repaint.
  • Store timer and listener handles on this so cleanup can actually reach them.

Practice Exercises

  1. The Cleanup Crew: Write a component that starts a setTimeout in its connected callback and clears it in its disconnected callback.
  2. 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.
  3. The Logger: Add logs to every lifecycle hook of a component and move it around the DOM using appendChild to see which hooks trigger.