
Custom Element Lifecycle and Reflection
A custom element is code the browser calls, not a framework schedules. The upgrade model, the lifecycle callbacks and their timing traps, attribute reflection, and cleanup.
TL;DR: A custom element is code the browser calls, not code a framework schedules — and getting its lifecycle right is the floor everything else in a component library stands on. This article covers the registration and upgrade model, the connected, disconnected, attribute-changed and adopted callbacks and their exact timing traps, the attribute-and-property reflection contract with its infinite-loop hazard, the pre-upgrade property pattern, and the cleanup discipline that keeps a long-lived page from leaking. Get this correct and idempotent, and the rest of the library is additive.
The registration and upgrade model
A custom element enters the world through a single call that binds a tag name to a class:
class MyToggle extends HTMLElement { /* ... */ }
customElements.define('my-toggle', MyToggle);The subtlety a framework normally hides is that the element can already exist in the document before its definition loads. The parser happily creates a <my-toggle> as an undefined element (a plain HTMLElement waiting for its definition), and when define runs — perhaps after an async chunk arrives — the browser upgrades every matching element already in the tree. Your class therefore has to assume it may be constructed for an element that a user has already been looking at, and possibly already interacted with.
Two registration paths exist, and only one is worth building on. Autonomous custom elements extend HTMLElement and are Baseline Widely available (since July 2022, per web-features; as of Nov 2026). Customized built-in elements — extending a native element such as a button and using an is= attribute — are not universally implemented; the WebKit team said in 2016 that it would not implement them, and WebKit's standards position on the feature is 'oppose' (as of Nov 2026 — an opinion on the specification, not an implementation status), so treat the pattern as non-Baseline and reach for an autonomous element that manages its own semantics instead (as of Nov 2026, per web-features; re-verify current support rather than trusting a fixed list). The constructor is the most restricted moment in the element's life. It must not inspect the element's attributes or children, because in the non-upgrade case (for example document.createElement) none will be present and relying on upgrades makes the element less usable. It must not add any either, because callers of createElement and createElementNS expect an empty element. Beyond that, the HTML Standard's guidance is to defer work to connectedCallback as much as possible and to use the constructor for initial state, default values, event listeners and possibly a shadow root.
The lifecycle callbacks and their timing
The browser calls back at fixed transitions. These are the four callbacks this article covers; the HTML Standard also defines connectedMoveCallback (covered with moves below) and, for form-associated custom elements, formAssociatedCallback, formDisabledCallback, formResetCallback and formStateRestoreCallback:
class MyToggle extends HTMLElement {
static observedAttributes = ['pressed'];
connectedCallback() { /* inserted into the DOM */ }
disconnectedCallback() { /* removed from the DOM */ }
attributeChangedCallback(name, oldValue, newValue) { /* observed attr changed */ }
adoptedCallback() { /* moved to a new document */ }
}A trap worth planning for is assuming connectedCallback fires exactly once, at a moment when the element's children are present. Neither is guaranteed. By default, moving an element within the DOM disconnects and reconnects it — an element that defines connectedMoveCallback and is moved with moveBefore() gets that callback instead (as of Nov 2026, web-features lists support for both in Chrome and Edge 133 and Firefox 144 but not in Safari, so neither is Baseline) — so connectedCallback can run more than once and must be idempotent. And it can run before the element's own light-DOM children have been parsed, so reaching for this.children inside it may find nothing. Setup that must happen once — attaching a shadow root, registering a global listener — needs a guard, and setup that depends on children needs to wait for them rather than assume them.
observedAttributes and the reflection contract
Attributes and properties are two different surfaces for the same element, and deciding which carries what is an API decision this foundation only has to make correctly for itself. Attributes are strings, meant for declarative and serializable configuration written in HTML. Properties are the rich runtime interface, able to hold objects and arrays. The observedAttributes array declares which attributes trigger attributeChangedCallback; changes to attributes not listed there do not call it.
When a value should be reachable both ways — settable in markup and readable as a property — you reflect it. The hazard is that naive reflection forms a loop: the property setter writes the attribute, which fires attributeChangedCallback, which sets the property, which writes the attribute again. Guarding the cycle is the discipline:
get pressed() { return this.hasAttribute('pressed'); }
set pressed(value) {
const on = Boolean(value);
if (on === this.hasAttribute('pressed')) return; // break the loop
this.toggleAttribute('pressed', on);
}Not every property should reflect to an attribute — reflect the ones that need to appear in the DOM for CSS or serialization, and keep rich values as properties only. The mechanics live here; which surface a given input belongs to is revisited from the API-design angle.
State that survives the element's life
Two failure modes come from the gap between when an element is used and when it is upgraded, and both have well-known remedies.
The first is the pre-upgrade property. A consumer — or a framework binding — may set a property on the element before its definition has loaded and upgraded it. A naive class defines the property as an accessor on its prototype, but the value the consumer already set is an own property of the instance, and that own property shadows the accessor — so the setter never runs and the value is never applied. The remedy is to capture and re-apply any own-properties at upgrade time:
connectedCallback() {
for (const prop of ['pressed', 'value']) {
if (this.hasOwnProperty(prop)) {
const v = this[prop];
delete this[prop]; // remove the instance property shadowing the accessor
this[prop] = v; // run it back through the setter
}
}
}The second is cleanup. Whatever an element registers on connect — event listeners on window or document, observers, timers, subscriptions — must be released in disconnectedCallback, or a page that mounts and unmounts the component many times leaks them. This is stated here as mechanics: register on connect, release on disconnect, keep the pairing symmetric. Chasing a leak that has already escaped is a browser-diagnostics task with its own tooling, and it is not this article's job.
Why this is the floor
Every other surface in a component library assumes an element that transitions correctly. Shadow-DOM styling attaches its root in a lifecycle that must fire predictably. Server rendering hands a pre-rendered element to an upgrade step that must match the rendered state. Form participation and accessibility both hang off an element whose connect and disconnect behave. When lifecycle is wrong, the symptoms do not stay local — they surface as flicker, as lost state, as leaks, as a component that works in isolation and fails in a real page, and the debugging can lead back here.
The mental model that keeps it correct is simple to state and worth repeating: the browser owns the lifecycle and calls you at fixed transitions, so your only job is to be correct and idempotent at each one. Build that floor well and this whole topic becomes a matter of adding capabilities to an element that already behaves.