# Web Components

> The Web Components is a set of web platform APIs for creating reusable custom elements with encapsulated functionality.

## What are Web Components and how do I create a custom element?

The set of standards that includes custom elements, shadow DOM and templates. Allows creating reusable elements with their own tags, styles and behavior that work in any framework or without it.

- Topic: Web Application
- Type: technology

## Example

Wrong:

```js
class MyCounter extends HTMLElement {
  onResize = () => this.update();
  connectedCallback() {
    window.addEventListener('resize', this.onResize);
  }
}
customElements.define('mycounter', MyCounter);
```

Right:

```js
class MyCounter extends HTMLElement {
  onResize = () => this.update();
  connectedCallback() {
    window.addEventListener('resize', this.onResize);
  }
  disconnectedCallback() {
    window.removeEventListener('resize', this.onResize);
  }
}
customElements.define('my-counter', MyCounter);
```

Custom element names need a hyphen, and listeners added in `connectedCallback` are removed when the element leaves the page.

## Common mistakes

- Expecting page class selectors to style elements inside the shadow root; only inherited properties and custom properties pass through.

## Key points

- Custom element names contain a hyphen, and `customElements.define()` is not called twice for one name.
- Listeners and timers added in `connectedCallback` are removed in `disconnectedCallback`.
- Attributes that change are listed in `observedAttributes` and handled in `attributeChangedCallback`.
- Interactive elements keep keyboard support, focus and an accessible name inside the shadow DOM.

## Interview questions

### Can I use Web Components inside a framework?

Yes. Custom elements are regular HTML elements, so most frameworks render them, though passing objects and listening to custom events may need extra code.

### Do Web Components need shadow DOM?

No. Custom elements work without it, and shadow DOM adds style and DOM encapsulation when you need it.

### How do I style a Web Component from outside?

Use CSS custom properties, which inherit into the shadow root, or `::part()` for elements the component exposes with a `part` attribute.

## Related cards

- [Shadow DOM](https://wonderium.dev/js/shadow-dom.md)
- [`<template>`](https://wonderium.dev/html/template.md)
- [`<slot>`](https://wonderium.dev/html/slot.md)
- [\[shadowrootmode\]](https://wonderium.dev/html/shadowrootmode.md)
- [\[exportparts\]](https://wonderium.dev/html/exportparts.md)

---

- Level: [Web Platform](https://wonderium.dev/web.md)
- HTML version: https://wonderium.dev/web/web-components
- Last updated: 2026-11-25
