What are Web Components? How do custom elements, Shadow DOM and slots work?
Web Components are browser standards for reusable, framework-independent elements.
The three parts
- Custom elements:
customElements.define('user-card', class extends HTMLElement {...}). Lifecycle callbacks areconnectedCallback,disconnectedCallback,attributeChangedCallback(for attributes listed instatic observedAttributes) andadoptedCallback. Names must contain a hyphen. - Shadow DOM:
this.attachShadow({ mode: 'open' })creates an encapsulated tree. Styles inside do not leak out and page styles do not leak in, except inherited properties (color, font) and CSS custom properties, which is how you theme them.::part()exposes chosen inner elements for styling. - Templates and slots:
<template>holds inert markup;<slot>and named slots project the light-DOM children into the shadow tree.
Where they fit
Design systems shared across React, Vue, Angular and plain pages (Shoelace/Web Awesome, Lit, Salesforce Lightning), and micro-frontends. Frameworks consume them: Vue supports them well, and React 19 added full support for passing properties and custom events.
Trade-offs
Server-side rendering needs Declarative Shadow DOM (<template shadowrootmode="open">). Forms need ElementInternals (static formAssociated = true) to take part in form submission and validation. Accessibility across shadow boundaries (ARIA references by id) is still awkward.
Example
class UserCard extends HTMLElement {
static observedAttributes = ['name'];
constructor() {
super();
this.attachShadow({ mode: 'open' }).innerHTML = `
<style>
:host { display: block; border: 1px solid var(--card-border, #ccc); padding: 12px; }
h3 { margin: 0; }
</style>
<h3></h3>
<slot name="actions"></slot>`;
}
attributeChangedCallback(name, _old, value) {
this.shadowRoot.querySelector('h3').textContent = value;
}
}
customElements.define('user-card', UserCard);<user-card name="Asha" style="--card-border: teal">
<button slot="actions">Follow</button>
</user-card>Follow-up questions interviewers ask
Try answering each one before you open it.
How does a custom element tell the outside world that something happened?
It dispatches a CustomEvent: this.dispatchEvent(new CustomEvent('follow', { detail: { id }, bubbles: true, composed: true })). composed: true lets the event cross the shadow boundary. Vue listens with @follow; React 19 with onfollow on the element.