attributeChangedCallback: Reactive Attributes
You'll learn how to make your custom element respond dynamically to attribute changes, creating truly reactive components.
The Core Idea
Once you've declared which attributes to observe (using observedAttributes), the attributeChangedCallback method fires whenever those attributes change. This is your opportunity to update internal state, recalculate values, and re-render your component—essentially making your element "reactive" to external changes.
Think of it like a thermostat: when someone adjusts the temperature dial (attribute), the thermostat (your callback) notices the change and adjusts the heating system (internal state and UI) accordingly.
How It Works
The callback receives three parameters:
name: which attribute changedoldValue: the previous value (ornullif first set)newValue: the new value (ornullif removed)
class ColorBox extends HTMLElement {
static get observedAttributes() {
return ['color', 'size'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue === newValue) return; // Skip if unchanged
if (name === 'color') {
this.style.backgroundColor = newValue;
} else if (name === 'size') {
this.style.width = newValue + 'px';
this.style.height = newValue + 'px';
}
}
}
customElements.define('color-box', ColorBox);
When someone changes <color-box color="red"> to <color-box color="blue">, the callback fires and immediately updates the styling. No manual event listeners needed—the element reacts automatically.
Best Practices
Always check if oldValue === newValue to avoid unnecessary work. This callback can fire even during initial parsing, so oldValue might be null. Handle null values gracefully and keep logic lightweight—heavy computation here can hurt performance.
Key Takeaway: attributeChangedCallback transforms observed attributes into reactive properties, automatically synchronizing your element's appearance and behavior with its HTML attributes.