Web components best practices for tags other developers can use
Make your tag behave like a built-in HTML element. Here are the web components best practices that get you there, from naming and events to accessibility, styling hooks, cleanup, and forms, each with a short example and the lesson it comes from.

A hotel guest never meets the people who built the room. They walk in and expect a light switch by the door, a lock that works, and a tap that runs hot on the left. If every room worked differently, guests would spend the night calling the front desk.
A web component that other developers use is that room. They didn't build it, and they shouldn't have to read its code to use it.
The best practices for web components come down to one rule: make your tag behave like a built-in HTML element. Give it a prefixed name, pair simple attributes with properties, send news out with events, build on real elements so it's accessible, offer custom properties and parts for styling, clean up when it leaves the page, and join forms the way an input does. Each practice below links to the lesson in the web components tutorial that teaches it.
Why should a component behave like a built-in element?
Because developers already know how built-in elements behave. They expect a setting to work as an attribute and as a property, the hidden attribute to hide the element, and events to reach a listener higher up the page. When your tag follows the same rules, there's nothing new to learn.

Naming and registering your tag
A custom element's name must be lowercase and contain a hyphen. Stick to lowercase letters, digits, and hyphens, which work in every browser.
Start every name with a prefix for your library, like tea- for a tea shop's kit. A page has one registry, and each name can be in it once. If two libraries both define my-button, the second define() throws a NotSupportedError. A prefix makes a clash unlikely, and scoped registries give one part of the page its own list of names.
End each component's file with its define() call, so loading the file registers the tag. If the file might load twice, say from two bundles, ask the registry first:
export class TeaTimer extends HTMLElement {
// …
}
if (!customElements.get("tea-timer")) {
customElements.define("tea-timer", TeaTimer);
}
Your first custom element explains the naming rules, and loading definitions on demand covers the guard.
Pairing attributes with properties
People set up a component with attributes in HTML and properties in JavaScript. Support both for every simple setting, like a word, a number, or an on and off value, and make the property reflect the attribute so the two always agree. A few more rules:
- Rich data is a property only. An attribute is always text, so an object written into one arrives as
[object Object]. - Booleans follow HTML's rule. The attribute being there means true, even
iced="false". Read it withhasAttribute()and write it withtoggleAttribute(). - Don't reflect values that change many times a second, like a timer's seconds left, or add attributes the page didn't write.
- Accept properties set before your class loads. An early value hides your setter, so pass it through the setter in
connectedCallback().
class TeaCup extends HTMLElement {
get iced() {
return this.hasAttribute("iced");
}
set iced(value) {
this.toggleAttribute("iced", Boolean(value));
}
connectedCallback() {
// The page may have set cup.iced before this class loaded.
if (Object.hasOwn(this, "iced")) {
const value = this.iced;
delete this.iced;
this.iced = value;
}
}
}
See attributes and properties, boolean, number, and enum attributes, and properties set before the upgrade.
Sending events out
Properties carry what the page wants. Events carry what happened inside your component that the page couldn't see, like a click on its button or a timer running out. Don't dispatch for a change the page made itself: a built-in input stays quiet when a script sets its value.
When you do dispatch:
- Name the event in lowercase with your prefix, like
tea-timer-done. Leave outon, and don't reuse a built-in name likechange, because everychangelistener above your component will hear it. - Set
bubbles: true, so one listener on a parent hears every copy of your component, andcomposed: true, so the event still gets out when your component sits in another component's shadow root. - Update your own state first.
dispatchEvent()runs every listener before it returns. - Tell people to listen with
addEventListener(). Anontea-timer-doneattribute does nothing.
this.dispatchEvent(
new CustomEvent("tea-timer-done", {
detail: { seconds: this.seconds },
bubbles: true,
composed: true,
}),
);
Dispatching events covers naming and detail, and composed events shows how events cross shadow roots.
Building accessibility in
Use real elements inside your component. A <button> in a shadow root still takes focus with Tab, turns Enter and Space into clicks, and keeps its role and name. A <div> styled like a button has none of that. Screen readers read shadow DOM like the rest of the page, so real elements work there. Accessibility and shadow DOM shows this, and common mistakes like aria-hidden on the host, which hides everything inside.
When the host itself is the control, like a switch, give it a default role and state through ElementInternals. They reach screen readers without writing attributes on a tag the page owns, and the page's own role and aria-* attributes still win:
class TeaToggle extends HTMLElement {
#internals = this.attachInternals();
constructor() {
super();
this.#internals.role = "switch";
this.#internals.ariaChecked = "false";
}
}
For focus, a component that wraps a real control attaches its shadow root with delegatesFocus: true, so a click anywhere on it lands on the control inside. A host that is the control takes tabindex="0" instead, unless the page wrote one. See ARIA with ElementInternals, focus delegation, and labels and descriptions.
Giving the page styling hooks
Shadow DOM keeps the page's CSS rules out, so plan how people will style your component:
- Custom properties for theme values, like colors and spacing. They inherit into shadow roots, so one line on
bodysets every copy. Prefix them and name them for their job, like--tea-card-accentrather than--tea-card-green, since a page may set it to brown. - Parts for a few high-level elements, like a heading or a button. The page styles them with
::part()and any CSS property. Each part name is public, so name it for its job. - Custom states for state that only matters to styling, like ready. The component turns it on with
internals.states.add(), and CSS reads it with:state().
Also give the host a display, because a custom element is inline by default and ignores width and height. Then add a :host([hidden]) rule, because your display beats the browser's rule for hidden. Styling the host explains both.
/* In the shadow root, beside <h3 part="name"> */
:host {
display: block;
}
:host([hidden]) {
display: none;
}
h3 {
color: var(--tea-card-accent, seagreen);
}
Cleaning up when it leaves the page
connectedCallback() runs every time the element joins a page. Moving it with append(), or a framework sorting a list, disconnects it and connects it again. So make setup safe to run twice, and guard work that must happen once, like adding a button.
Timers and listeners on window or document outlive the element unless you stop them. Make a new AbortController on each connection, and abort it in disconnectedCallback(). One abort() removes every listener that got its signal, and the signal can clear a timer too:
class TeaTimer extends HTMLElement {
#controller;
connectedCallback() {
this.#controller = new AbortController();
const { signal } = this.#controller;
const interval = setInterval(() => console.log("tick"), 1000);
signal.addEventListener("abort", () => clearInterval(interval));
document.addEventListener("keydown", () => console.log("key"), { signal });
}
disconnectedCallback() {
this.#controller.abort();
}
}
Keep the constructor small: call super() first, and leave attributes and children for later. See connectedCallback and disconnectedCallback and what the constructor may do.
Joining forms like a native input
A custom input that its form ignores is a quiet bug: the user fills it in, and the value never reaches the server. Make it a form-associated custom element. Add static formAssociated = true, ask for the element's internals, and then:
- call
setFormValue()when the value changes, and the form sends it under the element'sname; - call
setValidity()with a message while the value is invalid, so the form won't submit, as with a required input; - reset the value in
formResetCallback(), and disable inner controls informDisabledCallback().
class TeaRating extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
#stars = 0;
get value() {
return this.#stars;
}
set value(stars) {
this.#stars = stars;
this.#internals.setFormValue(String(stars));
if (stars > 0) this.#internals.setValidity({});
else this.#internals.setValidity({ valueMissing: true }, "Pick a rating.");
}
connectedCallback() {
this.value = this.#stars;
}
formResetCallback() {
this.value = 0;
}
}
A form-associated element is also labelable, so a page's <label for> can point at it. Labels and descriptions shows that, and MDN's ElementInternals reference lists every form method.
Documenting what you promise
Every attribute, property, event, custom property, part, and state you expose is public API. Renaming one can break pages you'll never hear about. Describe each one with JSDoc tags like @cssprop and @csspart, and publish a custom elements manifest that editors and tools can read. When you must rename something, keep the old name working for a while. Designing a component API covers this, with an API checklist you can copy.
Where to go next
New to building components? Start the web components tutorial with what web components are, and these practices arrive one lesson at a time. Choosing how to build a shared part? Read web components vs React. If shadow DOM still feels like a mystery, shadow DOM vs the virtual DOM clears up the most common mix-up.


