Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 38 ยท Custom Elements

Custom Element Lifecycle Callbacks

Understand the four lifecycle callbacks of a custom element: connectedCallback, disconnectedCallback, attributeChangedCallback and adoptedCallback, with live examples and cleanup rules.

A custom element lives through several moments: it is created, added to a page, changed, moved, and removed. The browser calls special methods on your class at each moment. These are the lifecycle callbacks. They are the hooks where you set up work, react to changes and clean up after yourself.

There are four callbacks in the standard, plus the constructor. Lit wraps all of them with its own, friendlier lifecycle (covered in The Lit Update Lifecycle), but Lit still uses these four underneath, so you need to know them.

The four callbacks

Callback When the browser calls it
connectedCallback() Each time the element is inserted into a document
disconnectedCallback() Each time the element is removed from a document
attributeChangedCallback(name, oldValue, newValue) When an observed attribute is added, changed or removed
adoptedCallback() When the element is moved to another document, for example from an iframe

Notice "each time". An element that you move with append() is disconnected and connected again. So connectedCallback can run many times for one object, and the code inside must be safe to repeat.

Watching the lifecycle happen

The next example logs every callback. Press the buttons to add, move and remove the element, and watch the console panel.

Lifecycle logger

Here is what you will see. On load: constructor, then attribute mood : null -> calm (the attribute was set before the element was added). After "Add to A": connected. After "Move to B": disconnected and then connected again. This surprises many people. A move is a remove plus an insert.

stateDiagram-v2
  [*] --> Created: constructor
  Created --> Connected: connectedCallback
  Connected --> Disconnected: disconnectedCallback
  Disconnected --> Connected: connectedCallback
  Connected --> Connected: attributeChangedCallback

An element can switch between connected and disconnected many times.

connectedCallback: set up

Use connectedCallback to render, to read attributes, and to start anything that has to run while the element is on the page: event listeners on window or document, timers, observers, fetch requests.

Because it can run repeatedly, protect one-time work:

JavaScript
connectedCallback() {
  if (!this.hasRendered) {
    this.hasRendered = true;
    this.buildDom();
  }
  window.addEventListener("resize", this.onResize);
}

The DOM building runs once, while the listener is added every time the element connects.

disconnectedCallback: clean up

Whatever you start in connectedCallback that lives outside the element must be stopped in disconnectedCallback. Otherwise removed elements keep running timers and listeners, which wastes memory and CPU. This is the classic memory leak of web components.

A clock that cleans up

The counter shows that the timer count goes down when the clock is removed and up again when it returns. Without clearInterval, the number would climb every time you re-added the clock. Lit gives you the same pair as connectedCallback and disconnectedCallback (always call super.connectedCallback() when you override them in a LitElement).

attributeChangedCallback and observedAttributes

The browser only calls attributeChangedCallback for attributes you list in the static observedAttributes array. Others are ignored, which keeps the system fast. The callback receives the attribute name, the old value (or null) and the new value (or null when the attribute is removed). Attribute values are always strings or null.

It also runs once for every attribute that is present when the element is created from HTML. That is the way initial values reach your element. A deeper look at attributes versus properties comes in Attributes vs Properties.

adoptedCallback

adoptedCallback is rare. It fires when document.adoptNode(el) moves an element into a different document, for example from an iframe's document into the main one. Most components never need it. Know it exists, and leave it out unless you work with iframes or <template> content from another document.

Where does the render happen?

For a vanilla element, you decide. The usual pattern is: render once in connectedCallback and re-render from attributeChangedCallback and from property setters. For a Lit element, you only write render(), and Lit decides when to call it. That saves you from the repeated-connection and ordering bugs listed in this lesson.

Common mistakes

  • Doing one-time setup in connectedCallback without a guard. The element is moved and the content is duplicated.
  • Forgetting to remove window, document or timer listeners in disconnectedCallback.
  • Not listing an attribute in observedAttributes, then wondering why the callback is silent.
  • Reading this.children in connectedCallback of an element created by the parser. Children may not have been parsed yet if the script runs before the closing tag. Wait for DOMContentLoaded or use slots.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to an element when you call parent.append(el) on an element already in the document?

    Moving an element removes it and inserts it again, so you get a disconnect followed by a connect.
  2. 2. Which attributes trigger attributeChangedCallback?

    The browser checks the observedAttributes list, so unlisted attributes never reach the callback.
  3. 3. Why should you clear a setInterval in disconnectedCallback?

    The timer holds a reference to the element and runs forever unless you clear it.
  4. 4. What value does newValue have when an observed attribute is removed?

    Attribute values are strings, and a removed attribute reports null.

Summary

  • connectedCallback and disconnectedCallback run each time an element enters or leaves a document, so moving an element triggers both.
  • Set up outside resources in connectedCallback; release them in disconnectedCallback.
  • attributeChangedCallback needs static observedAttributes; values are strings or null.
  • adoptedCallback is only for moving elements between documents.
  • Lit hides most of this behind one render() method, but its lifecycle sits on these callbacks.

Next: Attributes vs Properties