The Custom Element Lifecycle
You'll learn: How custom elements respond to creation, insertion, removal, and attribute changes through four lifecycle callback methods.
Understanding the Lifecycle
Just like components in frameworks have lifecycle hooks, custom elements have built-in callback methods that fire at specific moments in their existence. Think of these as "notification events" that let your element react to what's happening to it in the DOM.
The Four Lifecycle Callbacks
connectedCallback()
Fires when your element is inserted into the DOM. This is where you typically set up event listeners, fetch data, or start timers. It's like the element saying "I'm alive and ready!"
disconnectedCallback()
Fires when your element is removed from the DOM. Clean up here: remove event listeners, cancel timers, or abort network requests. Think of it as your element's cleanup crew.
attributeChangedCallback(name, oldValue, newValue)
Fires when an observed attribute changes. You must define which attributes to watch using a static observedAttributes getter. This lets your element react to attribute updates, similar to props changing in a framework component.
adoptedCallback()
Fires when your element is moved to a new document (like being transferred into an iframe). This is rare but important for cross-document scenarios.
Why This Matters
These callbacks give you precise control over your element's behavior at each stage of its life. connectedCallback() and disconnectedCallback() are the most commonly used—they mirror the mount/unmount pattern you might know from React or other frameworks.
Key Takeaway: The custom element lifecycle provides four callback methods—connectedCallback(), disconnectedCallback(), attributeChangedCallback(), and adoptedCallback()—that let you respond to creation, insertion, removal, and changes to your element.