A component is a reusable part of an interface with its own structure, behavior, and styling. Instead of scattering markup and scripts across a page, define a unit once and give its consumers a clear interface. In a web application, components can render repeated UI while page components render screens, a router handles navigation, and a store manages shared state. section 7.1 section 15.1
A web component is an implementation of that pattern using browser capabilities, not a single “Web Components API.” Its custom element behaves like an HTML tag and participates in the DOM and event system. Components may be general-purpose, such as a rating widget, or specific to an application, such as a product-cart item. section 7.1 section 7.2
Listing 7.2 A CounterButton web component
class CounterButton extends HTMLElement {
#count; #1
constructor() {
super();
this.#count = 0; #2
}
connectedCallback() {
if (this.querySelector('button')) return; #3
const button = document.createElement('button');
button.textContent = 'Clicks: 0';
button.addEventListener('click', () => {
this.#count++; #4
button.textContent = `Clicks: ${this.#count}`;
});
this.appendChild(button);
}
}
customElements.define('counter-button', CounterButton);
The counter button shows the smallest useful stateful contract: register a custom element, create its button when connected, and keep a separate count in each instance. section 7.7
Keep the boundary explicit:
- Use attributes for values supplied in HTML, properties for complex JavaScript values, CSS custom properties for styling choices, and events to communicate outward. section 7.9 section 7.1
- Do not assume an attribute and a property stay synchronized; implement that behavior if consumers need it. section 7.9
- Access child DOM from connectedCallback rather than the constructor. Because connection can recur when an element moves, avoid creating duplicate children or listeners. section 7.9 section 7.7
A custom element still participates in the CSS cascade. Style its host deliberately, and consider what users see before an asynchronously loaded definition is registered; :not(:defined) can identify that state. Build the smallest component that owns a coherent job rather than turning every part of an application into one. section 7.7 section 15.1













