Web Components are a set of native browser APIs for building reusable, encapsulated custom HTML elements — framework-agnostic and standards-based. Three technologies combine:
Web Components are a set of native browser APIs for building reusable, encapsulated custom HTML elements — framework-agnostic and standards-based. Three technologies combine:
<template>, <slot>) — inert, reusable markup.class UserCard extends HTMLElement {
connectedCallback() { // lifecycle: runs when added to the page
const shadow = this.attachShadow({ mode: "open" }); // create shadow DOM
shadow.innerHTML = `
<style> h2 { color: blue; } </style>
<h2>${this.getAttribute("name")}</h2>
<slot></slot>
`;
}
}
customElements.define("user-card", UserCard); // name MUST contain a hyphen
<user-card name="Ann">Extra content goes in the slot</user-card>
The styles inside the shadow root are scoped — the page's CSS can't reach in, and the component's CSS can't leak out. This solves the global-CSS problem natively:
/* page CSS */ h2 { color: red; } /* does NOT affect the <h2> inside user-card */
connectedCallback() // added to DOM
disconnectedCallback() // removed from DOM (cleanup)
attributeChangedCallback(name, old, val) // an observed attribute changed
static get observedAttributes() { return ["name"]; }
Web Components let you build reusable widgets that work in any framework (or none) with real style/DOM encapsulation — ideal for design systems and micro-frontends shared across teams using different stacks.
They're how libraries like Shoelace ship framework-agnostic components.
The trade-offs (verbose API, SSR/styling complexity) mean app developers often still prefer React/Vue, but the platform primitive is powerful and standards-based.