completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

When to use web components, and when not

When to use web components and when not: sharing across frameworks, design systems, shadow or light DOM, the arguments against, and how they sit beside React.

By the end, you can
  • 01
    Decide when a web component fitsPick a web component for parts many apps share, a plain HTML element when one does the job, and your framework for one app's screens.
  • 02
    Weigh both sides of the debateExplain the main arguments for and against web components, who made them, and which ones have changed since.
  • 03
    Choose shadow DOM or light DOMSay what each one does to the page's styles and scripts, and use a web component inside a React app.

When should you use web components?

Ravi looks after the websites of Leaf and Kettle, the tea shop from the last lesson. The shop has grown. Asha builds its online shop with React. The staff page uses Vue. The tea blog is plain HTML. All three need the same star rating for each tea.

Ravi reads two posts about web components. One says to build everything with them. The other says they aren't the future. Should the rating be a web component? And what about the rest of the shop?

Use web components for parts that many apps, frameworks, or teams share, like a star rating or a design system's buttons. Use a plain HTML element when one already does the job. And keep the screens of one app in that app's framework.

Here is the rating Ravi builds, on a plain page:

A star rating on a plain pagePop out in the code editor (opens in a new tab)HTML
<h2>Green tea</h2><tea-rating value="4"></tea-rating> <script src="tea-rating.js"></script>
ResultLoading…
  • Line 1 is a normal heading.
  • Line 2 uses the new tag, <tea-rating>. Its value attribute says how many stars to fill.
  • Line 4 loads the tag's class from tea-rating.js, the second tab.

The result shows Green tea and four filled stars out of five: ★★★★☆. Click a star, and the rating changes. The class in the second tab makes five star buttons. You'll learn to write classes like it in stage 2. For now, one thing matters. To a page, <tea-rating> is one more HTML tag. So the React shop, the Vue staff page, and the blog can all use it.

That's the heart of the answer. Before Ravi builds anything, though, he should ask three questions, in order:

Choosing a tool, as three questions in a column. Does an HTML element do it? Yes: Use that element. Do many apps share it? Yes: A web component. Is it inside a framework app? Yes: The app's framework. No to all three: a small custom element.Does an HTML element do it?yesUse that elementnoDo many apps share it?yesA web componentnoIs it inside a framework app?yesThe app's frameworknoA small custom element
Ask the questions in order, and stop at the first yes. A web component is the answer when many apps share a part. A page with no framework that needs a little behavior gets a small custom element.

The rest of this lesson takes the questions one at a time. It also gives the case against web components, from the people who build frameworks.

Real-life analogyPrint the menu, handwrite the note

A tea shop prints its menu. Setting up the printer takes time, but hundreds of customers read each copy. A note for the cook is different. It's written by hand in a few seconds. Printing it would cost more than it saves.

In real life: Setting up the printer
In JavaScript: Writing a web component: a class, a tag name, attributes, and events
In real life: Hundreds of customers reading the menu
In JavaScript: Many apps and teams using the component
In real life: A note for the cook, written by hand
In JavaScript: A screen only one app shows, written in that app's framework

Lea Verou, who works on the Web Awesome component library, puts it this way. What matters is how many people use a component, compared with how many write it. A rating used on many sites earns the extra work. A screen used in one place doesn't.

The main idea

A web component pays off when many people use it. Reach for one when many apps, frameworks, or teams share a part. Use a built-in element when one does the job. Let your framework run the screens of one app.

Do you need a custom element at all?

The first question in the picture is the easiest to skip. Does HTML already have an element for this? Chrome's guide to web components starts there, with a section called "Decide whether you even need a custom element". It says the most common mistake is rebuilding a built-in element, like a homemade button.

Why is that a mistake? A tag's name tells the browser nothing about what it does. Here is a real button next to a tag that only looks like one:

A real button and a tag that only looks like onePop out in the code editor (opens in a new tab)HTML
<style>  tea-button { border: 2px solid; padding: 4px 8px; }</style> <button>Add to cart</button><tea-button>Add to cart</tea-button><p>Nothing added yet.</p> <script>  class TeaButton extends HTMLElement {}  customElements.define("tea-button", TeaButton);   const note = document.querySelector("p");  for (const item of document.querySelectorAll("button, tea-button")) {    item.addEventListener("click", () => {      note.textContent = `The ${item.localName} added a tea.`;    });  }</script>
ResultLoading…
  • Line 2 gives <tea-button> a border, so it looks like a button.
  • Line 5 is a real <button>. Line 6 is the <tea-button>.
  • Lines 10 and 11 define tea-button with an empty class.
  • Lines 14 to 18 give both of them a click listener. A click writes the tag's name into the paragraph.

Click each one with the mouse. Both work: the paragraph says The button added a tea., then The tea-button added a tea. Now try the keyboard. Click an empty part of the result, then press Tab. Focus lands on the real button. Press Enter, and it adds a tea. Press Tab again. Focus skips the tea-button: the keyboard can't reach it.

Screen readers miss it too. They read the accessibility tree, the browser's list of what each thing on the page is. In Chrome's tree, the real button has the role button. The tea-button is only generic, a box with text in it.

The HTML standard makes the same point with a tag called taco-button. Calling a tag that doesn't make it a button. Browsers, search engines, and screen readers won't treat it as one. To fix it by hand, you'd add focus, a role, a name, keyboard handling, and styles for when it's turned off.

Real-life analogyA door painted on a wall

A café paints a door on its wall. It has a handle and a sign, and it looks real. But nobody can open it. A real door opens with a push, and every visitor knows how to use it. If the café wants a new look, it paints a real door.

In real life: The painted door
In JavaScript: <tea-button>, styled to look like a button
In real life: Pushing the painted handle
In JavaScript: Pressing Tab and Enter, and nothing happens
In real life: A real door every visitor knows how to use
In JavaScript: <button>, which every browser, keyboard, and screen reader knows
In real life: A real door with a fresh coat of paint
In JavaScript: A real <button> wrapped in your own tag

So what should Ravi do? Use the real element. If the shop needs a button with an extra job, wrap a real button in the custom tag. It's the same fix as the order button in the last lesson:

A real button inside the tag, with one extra jobPop out in the code editor (opens in a new tab)HTML
<tea-button>  <button>Add to cart</button></tea-button> <script>  class TeaButton extends HTMLElement {    connectedCallback() {      const button = this.querySelector("button");      let count = 0;      button.addEventListener("click", () => {        count++;        button.textContent = `Added ${count}`;      });    }  }  customElements.define("tea-button", TeaButton);</script>
ResultLoading…
  • Lines 1 to 3 put a real <button> inside <tea-button>.
  • Line 8 finds that button. Line 9 starts a count at 0.
  • Lines 10 to 13 add one to the count on each click, and show it on the button.

Press Tab, then Enter twice. The button says Added 2. Focus, Enter, Space, and the button role all come from the real <button>. The custom tag only adds the count.

The same goes for other parts. Cassondra Roberts, who wrote the first version of Chrome's guide, lists jobs that HTML already does better than a component:

  • a box that opens and closes: <details> and <summary>;
  • a pop-up window: <dialog>;
  • a menu that shows over the page: the popover attribute.

A new look alone doesn't call for a custom element. Chrome's guide gives the test: build one when the part needs its own state, a JavaScript API, or behavior HTML can't give.

How can one component work in every framework?

The second question was: do many apps share it? Ravi's rating passes that test. Three sites, built three ways, all need it. How can one tag serve all three?

Every framework already knows how to talk to an HTML element. It sets the element's attributes and properties, and it listens for its events. A web component speaks that same language. Data goes in as attributes, and news comes out as events:

A value goes in, an event comes outPop out in the code editor (opens in a new tab)HTML
<tea-rating value="3"></tea-rating><p>No new rating yet.</p> <script src="tea-rating.js"></script><script>  const rating = document.querySelector("tea-rating");  const note = document.querySelector("p");  rating.addEventListener("rating-change", (event) => {    note.textContent = `You gave it ${event.detail} stars.`;    console.log("rating-change", event.detail);  });</script>
ResultLoading…
  • Line 1 sends a value in: value="3".
  • Line 4 loads the same tea-rating.js.
  • Line 8 listens for an event called rating-change.
  • Line 9 writes the new rating into the paragraph. event.detail holds the number of the star you clicked.
  • Line 10 prints it too.

Click the fifth star. All five stars fill, the paragraph says You gave it 5 stars., and the console prints rating-change 5. Where does the event come from? In the tea-rating.js tab, line 12 sets the value attribute, and line 13 sends the event with new CustomEvent(). A custom event is an event your own code names, with any data you like in detail.

Real-life analogyTea in standard crates

A tea farm packs its tea in crates of one standard size. Delivery vans, shop shelves, and café storerooms are all built to fit that size, whoever made them. So the farm packs once, and every buyer can take the crates.

In real life: A crate of the standard size
In JavaScript: An HTML element, which every framework knows
In real life: The tea inside the crate
In JavaScript: Your component's code
In real life: Vans and shelves from many makers
In JavaScript: React, Vue, Angular, and plain HTML pages
In real life: Packing the tea once
In JavaScript: Writing the component once

Supporters of web components point to sharing first. Nolan Lawson worked for years on LWC, Salesforce's web components framework. He names three kinds of part that fit them well:

  • Self-contained widgets, like a calendar or a color picker. His own <emoji-picker> needs one line to load and one tag to use.
  • Glue between frameworks. A team moving to a new framework can mix old and new parts, instead of rewriting everything at once.
  • Design systems in big companies, where apps built with many frameworks must look the same.

Chrome's guide adds one more: a widget dropped into pages your framework doesn't control. Say partner cafés want a tea-of-the-day box on their own sites. Each site is built a different way, and one tag works in all of them.

Why do design systems use web components?

A design system is a company's shared set of parts: colors, fonts, buttons, form fields, and the rules for using them. Every app the company builds uses it. So the system has to last longer than any one app.

Brad Frost helps big companies build design systems. For the core of a design system on the web, he recommends one technology: web components. They're part of the web platform, so they work with any framework, or none. His team builds them with Lit, a small library for writing web components.

A design system in three layers. At the bottom, a core of web components: <tea-button>, <tea-rating>, <tea-card>. In the middle, an optional React wrapper and Vue wrapper. At the top, the products: the shop uses the React wrapper, the staff page uses the Vue wrapper, and the blog uses the web components with no wrapper.shopReact wrapperstaff pageVue wrapperblogno wrapperweb components<tea-button><tea-rating><tea-card>
The design system's components are web components, at the bottom. Framework wrappers in the middle are optional. The blog uses the components with no wrapper at all.

The picture shows his layers. At the bottom are the web components. Above them, a team may add a thin wrapper for one framework. For example, a React wrapper can offer <DsButton> for the web component <ds-button>. Wrappers are optional. Brad Frost expects them to matter less over time, because most frameworks can use web components as they are.

Real-life analogyBuilt-in shelves outlast the furniture

A tea shop changes its tables and chairs every few years, as tastes change. The shelves built into the walls stay. Each new set of furniture is chosen to fit around them.

In real life: The shop's walls
In JavaScript: The browser
In real life: Shelves built into the walls
In JavaScript: The design system's web components
In real life: Tables and chairs
In JavaScript: The framework each app uses today
In real life: New furniture placed around the same shelves
In JavaScript: A new framework using the same components

Why do web components last? Because browsers keep old code working. Jake Lazaroff points to the Space Jam website from 1996, which still works in today's browsers. He wrote the live demos on his blog as plain web components, so they would work on any site that shows HTML. His blog had already moved many times, from WordPress to Astro.

Nolan Lawson makes the same point for big companies. Updating a framework can cost a team weeks of rewriting. But connectedCallback stays connectedCallback: the browser makers keep it working. Adobe's Spectrum Web Components and Red Hat's PatternFly Elements are design systems built this way. Cassondra Roberts worked on both. You'll build one for the tea shop in stage 12.

What are the arguments against web components?

Not everyone agrees with all of this. Some of the strongest arguments against web components come from people who build frameworks. They're worth knowing. Some still hold, and some have changed.

Rich Harris, 2019

Rich Harris created Svelte, a framework. In 2019 he wrote "Why I don't use web components". He said they have real uses, and explained why he doesn't use them. His main points were:

  • They show nothing until JavaScript runs.
  • Shadow DOM styles had to sit in strings inside JavaScript.
  • Some browsers needed polyfills.
  • Attributes and properties are confusing, and a component has to handle both.
  • Writing one by hand takes far more code than in a framework.
  • A page has one list of tag names, so names can clash.

Ryan Carniato, 2024

Ryan Carniato created Solid, another framework. He used web components at work for seven years. In 2024 he wrote "Web Components Are Not the Future". His main point is that elements are not components. A framework component can disappear when the page is built. A web component is always a real element on the page. So everything it takes in goes through the DOM, as attributes and properties, and that costs time. He adds that there's no standard way to render them on a server, so each tool does it differently.

You can test the attribute point yourself. An attribute always holds a string:

Whatever goes into an attribute comes out as a stringPop out in the code editor (opens in a new tab)HTML
<tea-rating value="4"></tea-rating> <script src="tea-rating.js"></script><script>  const rating = document.querySelector("tea-rating");  rating.setAttribute("value", 2 + 3);  console.log(typeof rating.getAttribute("value"));  rating.setAttribute("tea", { name: "Green tea" });  console.log(rating.getAttribute("tea"));  rating.tea = { name: "Green tea" };  console.log(rating.tea.name);</script>
ResultLoading…
  • Line 6 sets value to 2 + 3, the number 5. All five stars fill.
  • Line 7 prints string. The attribute stored the text "5", not the number.
  • Line 8 tries to store an object in an attribute. Line 9 prints [object Object]: the object became text, and its data is gone.
  • Line 10 sets a property instead. A property is a plain JavaScript value on the element object, so it can hold anything. Line 11 prints Green tea.

So a component that takes rich data needs properties too, and a framework has to know which one to use. React 19 checks whether the element has a property with that name. That's the extra work Ryan Carniato means. For more on the two, see attributes and properties.

The replies

Nolan Lawson replied to Ryan Carniato two days later. He agreed that the DOM costs time, and that the fastest framework avoids extra elements. But speed isn't everything, he wrote. Teams also weigh how easy the code is to keep working, and accessibility. He agreed on one thing more: web components are bad at replacing every framework.

Lea Verou wrote that the two sides mean different kinds of components. Some are general parts any site could use, like tabs or a rating. Others belong to one project. Web components help the first kind most. She agreed that writing them by hand, without a library like Lit, is still painful. Cory LaViska replied that web components aren't meant to do everything a framework does. They're a lower-level element that any framework can share.

The debate goes on

In October 2026, Nolan Lawson asked a new question. Do web components have a future if AI tools write most of the code? Reuse matters less when a tool can rebuild a part from a short request. He still sees two uses: separate teams' parts on one page, and parts worth sharing, like his emoji picker. He also listed three gaps that are still open: server rendering, sharing style sheets, and accessibility.

Cassondra Roberts replied the next day. The native-first advice in Chrome's guide was on purpose, she wrote. AI tools tend to build a new component where plain HTML would do. But she still sees a clear job for web components: shared design system parts, widgets for other people's pages, and anything that has to work across frameworks.

Developers who use web components name similar pains. In the State of HTML 2025 survey, 3,232 people picked their top pain points. About half picked "excessive complexity". More than a third picked leaning on JavaScript and server rendering. Nearly a third picked accessibility.

Where each argument stands now

Read each row across: the argument, who made it, and where it stands today.

The arguments against web components
The argumentWho made itWhere it stands now
A web component shows nothing without JavaScript.Rich Harris, 2019.Still true when a component builds everything in JavaScript. Light DOM content and declarative shadow DOM show without it.
You need polyfills.Rich Harris, 2019.Not any more. Every major browser has had the core parts since 2020.
Shadow DOM styles have to sit in strings inside JavaScript.Rich Harris, 2019.Constructable style sheets work in every browser now, so many shadow roots can share one real style sheet.
One list of tag names for the whole page means names clash.Rich Harris, 2019.Scoped registries fixed this. They reached every browser in October 2026.
Data goes in through attributes, and attributes are strings.Rich Harris, 2019, and Ryan Carniato, 2024.Still true. Rich data has to go through properties instead.
Every component is a real element, and the DOM costs time.Ryan Carniato, 2024.True. Nolan Lawson agrees, and answers that speed is only one of the things a team weighs.
Server rendering has no standard way.Ryan Carniato, 2024, and Nolan Lawson, 2023 and 2026.Half true. Declarative shadow DOM is standard HTML, but each library renders on the server its own way.
Accessibility across shadow roots is hard.Nolan Lawson, 2023 and 2026.Half solved. Reference Target, a missing piece, is on by default only in Chrome.
Writing them by hand is slow and full of traps.Lea Verou, 2024.Libraries such as Lit make it shorter. Stage 8 teaches Lit.

So both sides are right about something. Inside one app, a web component adds costs a framework component doesn't have. Shared between many apps, those costs buy one part that works everywhere. That's the same answer the picture at the top gives.

Should a web component use shadow DOM or light DOM?

Ravi's next choice is inside the component. Where should its HTML live? There are two places:

  • Light DOM is the page's own tree. A component that writes HTML into itself, or wraps HTML from the page, uses light DOM.
  • Shadow DOM is a private tree attached to the element, like the shadow root in the first lesson. The page's CSS rules and scripts can't reach inside it by accident.

This playground puts one tea card on the tea blog. The blog's CSS has a .name rule for its bylines. The card happens to use .name for the tea's name too. Switch between the two choices. Only line 12 changes:

Playground: the blog's CSS meets the tea card
The blog's CSS and a tea cardPop out in the code editor (opens in a new tab)HTML
<style>  .name { color: gray; font-style: italic; }  tea-card { --tea-accent: green; }</style> <p class="name">By Ravi</p><tea-card></tea-card> <script>  class TeaCard extends HTMLElement {    connectedCallback() {      const root = this;      root.innerHTML = `<h3 class="name">Green tea</h3>        <p style="color: var(--tea-accent)">Brew for 3 minutes</p>`;    }  }  customElements.define("tea-card", TeaCard);  console.log(document.querySelectorAll(".name").length);</script>
ResultLoading…
Try it yourself
The blog's .name rule turns the tea name gray and italic

Line 12 puts the card's heading in the page's own tree. So the blog's .name rule on line 2 picks it out too, by accident. Line 18 finds two .name elements. Brew for 3 minutes is green, from --tea-accent on line 3.

Both choices are the same page. Only line 12 changes: the card writes its inside into itself, or into a shadow root. Each run starts a fresh page.
  • Line 2 is the blog's rule: anything with the class name is gray and italic.
  • Line 3 sets --tea-accent on every tea card. It's a custom property: a CSS variable you name yourself, starting with two hyphens.
  • Line 6 is the blog's byline, By Ravi.
  • Line 12 picks where the card's HTML goes: into the card itself (this), or into a new shadow root.
  • Lines 13 and 14 write a heading and a paragraph. The paragraph's color comes from --tea-accent.
  • Line 18 counts the .name elements the page's own code can find.

With Light DOM, the tea name turns gray and italic. The blog's rule picked it out by accident, and line 18 prints 2. With Shadow DOM, the tea name keeps its own look, and line 18 prints 1. In both, Brew for 3 minutes is green. A custom property is inherited, so it passes into a shadow root.

Two tea cards on the same blog page. Left, light DOM: the blog's .name rule reaches the card's h3 and turns it gray and italic, and --tea-accent turns its p green. Right, shadow DOM: the .name rule stops at the shadow root, so the h3 stays black, while --tea-accent still reaches the p and turns it green..name rule--tea-accentlight DOMh3.name<p>gray, italicgreenLight DOM.name rule--tea-accentshadow rooth3.name<p>blackgreenstopsShadow DOM
In light DOM, every page rule that matches reaches inside. A shadow root stops the page's rules, but lets custom properties like --tea-accent through.
Real-life analogyHooks in a rented flat

In a rented flat, you hang pictures only on the hooks the landlord put up. You can't knock down a wall. In return, the landlord can fix the pipes without asking you, and your pictures stay where they are. In your own house, you can change anything. But your changes can clash with the next repair.

In real life: The landlord
In JavaScript: The component's author
In real life: The tenant
In JavaScript: The page that uses the component
In real life: The hooks on the wall
In JavaScript: Custom properties and ::part()
In real life: Fixing the pipes without asking
In JavaScript: Changing the component's inside in a new version
In real life: Your own house
In JavaScript: Light DOM, where the page can style everything

Nolan Lawson explains why both choices exist. A component's author wants to change the inside later without breaking anyone. A page's author wants to style everything. Shadow DOM sides with the component's author. The page gets only the hooks the author offers: custom properties, and ::part(), which styles a part the author names. Light DOM sides with the page.

Which matters more depends on the site, he says. A campaign page that will be rebuilt in two years can style whatever it likes. A design system, or an app that must last for years, gains more from shadow DOM.

HTML web components

Light DOM has one more strength. HTML written in the page shows before any JavaScript runs. Jeremy Keith calls a custom tag that wraps real HTML an HTML web component. He suggests starting there, and keeping shadow DOM as a last resort. Here is one for the shop:

A custom tag that adds one job to real HTMLPop out in the code editor (opens in a new tab)HTML
<tea-total price="4">  <label>Cups <input type="number" value="1" min="1"></label>  <output>Total: 4</output></tea-total> <script>  class TeaTotal extends HTMLElement {    connectedCallback() {      const input = this.querySelector("input");      const output = this.querySelector("output");      const price = Number(this.getAttribute("price"));      input.addEventListener("input", () => {        output.textContent = `Total: ${price * input.value}`;      });    }  }  customElements.define("tea-total", TeaTotal);</script>
ResultLoading…
  • Lines 1 to 4 are real HTML: a label, a number box, and an output, all inside <tea-total>.
  • Lines 9 and 10 find the box and the output. They're in light DOM, so this.querySelector() finds them.
  • Line 11 reads the price, 4.
  • Lines 12 to 14 work out the total each time the number changes.

Type 3 in the box. The output says Total: 12. Now press Edit & run and delete lines 6 to 18, the whole script. The page still shows the label, the box, and Total: 4. Without JavaScript, the reader still sees the price. For this kind of component, that answers Rich Harris's first point. Chrome's guide gives the same advice for a lot of markup with a little behavior: keep the markup in light DOM, and let a small custom element add to it.

Read each row across: a question, then the answer for light DOM and for shadow DOM.

Light DOM or shadow DOM
QuestionLight DOMShadow DOM
Can the page's CSS rules style the inside?Yes. Any rule that matches picks it out, on purpose or by accident.No. Only inherited styles, custom properties, and parts the author names reach inside.
Can page scripts find the inside with querySelector()?Yes. It's part of the page's own tree.No. Code has to go through element.shadowRoot, and only an open root has one.
Does the inside show before JavaScript runs?Yes, when the HTML is written in the page.Only with declarative shadow DOM. Otherwise it waits for the script.
Can the author change the inside without breaking pages?It's risky. Pages may lean on its classes and its structure.It's safer. Pages can only lean on the hooks the author offers.
Which kind of component fits it?A component that wraps real HTML on your own site.A shared component that must look the same everywhere.

Lesson 6.4 in stage 3 goes deeper into this choice, and stage 4 covers styling across the boundary.

Do web components replace React?

Back to the shop. Should Asha rebuild the whole React shop as web components? No. Web components sit next to a framework, not in its place.

Each one does a different job. A framework like React runs an app. It keeps data in state, moves between screens, and draws the page again when the data changes. A web component gives you a new tag. Lea Verou calls "frameworks vs web components" a false choice: frameworks already use HTML elements, and web components add more of them. Think of a café's order system and its teacups. The order system tracks tables and bills. The cups only hold tea, and any order system can use them.

Here is the rating inside a React component. React keeps the number; the web component shows the stars:

The same rating inside a React componentPop out in the code editor (opens in a new tab)JSX
import { useState } from "react";import "./tea-rating.js"; export default function Review() {  const [stars, setStars] = useState(4);  return (    <section>      <h2>Review Green tea</h2>      <tea-rating value={stars} onrating-change={(event) => setStars(event.detail)} />      <p>React has {stars} stars in its state.</p>    </section>  );}
ResultLoading…
  • Line 2 imports tea-rating.js, the same file as before. Importing it runs its define() line.
  • Line 5 keeps the number of stars in React's state, starting at 4.
  • Line 9 renders <tea-rating>. The element has no value property, so React sets value as an attribute. onrating-change listens for the rating-change event: React takes the name after on exactly as written.
  • Line 10 shows the number React holds.

Click the second star. The event reaches React, setStars(2) runs, and the paragraph says React has 2 stars in its state. React then sends the new value back down to the rating. React 19 fully supports custom elements, as the first lesson showed.

One file, tea-rating.js, with arrows to three sites: the shop built with React, the staff page built with Vue, and the blog in plain HTML. Each site shows the same tea-rating tag. Only the React shop also has a Checkout component.tea-rating.jsshop<tea-rating><Checkout>Reactstaff<tea-rating>Vueblog<tea-rating>plain HTML
One file gives all three sites the same <tea-rating>. The checkout belongs to the shop alone, so it stays a React component.

So when does the framework win? Cassondra Roberts lists the cases. The app itself is the product. A lot of data is shared across many screens, changes often, or has to stay in step with the page. The app moves between screens in the browser. Or the team knows a framework well. Chrome's guide says the same from the other side. If an app already uses React, Vue, or Svelte, build its own screens with that framework. Reach for a custom element when a part must leave that app, or outlive it.

That's Leaf and Kettle's answer. The rating is a web component, because three sites share it. The checkout stays a React component, because only the shop has it. Stage 10 covers web components in each framework.

Choosing for the tea shop's parts

Now decide for the rest of the shop. Use the three questions from the picture at the top. Does an HTML element do it? Do many apps share it? Is it inside one framework app? Sort each part:

Web component, framework, or plain HTML?
  • The star rating on the React shop, the Vue staff page, and the blog
  • A tea-of-the-day box that partner cafés paste into their own sites
  • The design system's product card, for the shop and the staff page
  • The checkout steps, which only the React shop has
  • The staff page's order table with filters
  • A box that opens to show a tea's long description
  • A button that only changes color when you point at it
  • A pop-up with brewing tips
Try it yourself
0 of 8 correct

Sort each part of the tea shop by what should build it.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Here is the whole decision as a checklist you can use on any project:

  1. Look for a built-in element first: <button>, <details>, <dialog>, or popover.
  2. If many apps, frameworks, or other people's pages need the part, make it a web component.
  3. If one app owns it, write it in that app's framework.
  4. Use light DOM when the page should style the inside. Use shadow DOM when the part must look the same everywhere.
  5. Send simple values in as attributes and rich data as properties. Send news out as events.

Common mix-ups

  • "A tag named tea-button works like a button." No. A name gives a tag no meaning. The keyboard skips it, and screen readers don't call it a button. Wrap a real <button> instead.
  • "Web components should replace your framework." No. They sit next to it. The framework runs the app, and a web component is one tag inside it.
  • "Web components make pages faster." No, not on their own. Edge's team credits its faster interface to building it from HTML first, with less JavaScript at startup. And each component is a real element, which costs a little time.
  • "Web components can't be rendered on a server." No. Declarative shadow DOM writes a shadow root in HTML, and light DOM content is HTML already. What's missing is one standard way for every library to do it.
  • "Every web component needs shadow DOM." No. Shadow DOM is optional. An HTML web component like <tea-total> wraps light DOM HTML.
  • "Shadow DOM blocks every style from the page." No. Inherited styles like the text color, and custom properties like --tea-accent, pass inside.

Practice exercises

Answer first, then use the hints. The live results let you check yourself.

Exercise 1 · Warm-upWhich one can the keyboard reach?

What does line 9 print?

<button>Add to cart</button><tea-button>Add to cart</tea-button> <script>  class TeaButton extends HTMLElement {}  customElements.define("tea-button", TeaButton);   console.log(document.querySelector("button").tabIndex);  console.log(document.querySelector("tea-button").tabIndex);</script>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upA number in, a string out

    What does line 3 print?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const rating = document.createElement("tea-rating");
    rating.setAttribute("value", 4);
    console.log(typeof rating.getAttribute("value"));

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticePick the right tool

      Which of these parts should Leaf and Kettle build as a web component?

      1. A box that opens to show a tea's long description, on one blog post.
      2. The checkout steps inside the React shop.
      3. A tea-of-the-day box that partner cafés paste into their own sites.

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeLet the blog pick the color

        The blog sets --tea-name-color: green, but the tea name stays black. Change the card's style so the page can pick the color. What color is the tea name then?

        <style>  tea-card { --tea-name-color: green; }</style> <tea-card></tea-card> <script>  class TeaCard extends HTMLElement {    constructor() {      super();      const root = this.attachShadow({ mode: "open" });      root.innerHTML = `<style>h3 { color: black; }</style>        <h3>Green tea</h3>`;    }  }  customElements.define("tea-card", TeaCard);</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeA tip that shows without JavaScript

          The blog's <tea-tip> only builds its text in JavaScript, and its script failed to load. The page shows nothing. Rewrite line 1 so the tip shows without the script. What does the page show?

          <tea-tip text="Use water just below boiling."></tea-tip> <!-- The script failed to load: --><!-- <script src="tea-tip.js"></script> -->
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeSend the tea as an object

            This card shows [object Object]. Change it to take the tea through a property, so it shows the tea's name and minutes. What does the card show?

            <tea-card></tea-card> <script>  class TeaCard extends HTMLElement {    static observedAttributes = ["tea"];     attributeChangedCallback(name, oldValue, newValue) {      this.textContent = newValue;    }  }  customElements.define("tea-card", TeaCard);   const card = document.querySelector("tea-card");  card.setAttribute("tea", { name: "Green tea", minutes: 3 });</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask: does a built-in element do it, do many apps share it, or does one app own it?

              The when to use web components quiz · 8 questionsScore: first tries count
              1. Question 1 of 8Leaf and Kettle's star rating is used by a React shop, a Vue staff page, and a plain HTML blog. What fits best?

                Choose an answer to see the explanation.

              2. Question 2 of 8A blog post needs a box that opens to show more text. What should you reach for first?

                Choose an answer to see the explanation.

              3. Question 3 of 8In the painted button example, where does focus land after one press of Tab?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <style>
                  tea-button { border: 2px solid; padding: 4px 8px; }
                </style>
                
                <button>Add to cart</button>
                <tea-button>Add to cart</tea-button>
                <p>Nothing added yet.</p>
                
                <script>
                  class TeaButton extends HTMLElement {}
                  customElements.define("tea-button", TeaButton);
                
                  const note = document.querySelector("p");
                  for (const item of document.querySelectorAll("button, tea-button")) {
                    item.addEventListener("click", () => {
                      note.textContent = `The ${item.localName} added a tea.`;
                    });
                  }
                </script>

                Choose an answer to see the explanation.

              4. Question 4 of 8In the shadow DOM version of the tea card, what does line 18 print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <style>
                  .name { color: gray; font-style: italic; }
                  tea-card { --tea-accent: green; }
                </style>
                
                <p class="name">By Ravi</p>
                <tea-card></tea-card>
                
                <script>
                  class TeaCard extends HTMLElement {
                    connectedCallback() {
                      const root = this.attachShadow({ mode: "open" });
                      root.innerHTML = `<h3 class="name">Green tea</h3>
                        <p style="color: var(--tea-accent)">Brew for 3 minutes</p>`;
                    }
                  }
                  customElements.define("tea-card", TeaCard);
                  console.log(document.querySelectorAll(".name").length);
                </script>

                Choose an answer to see the explanation.

              5. Question 5 of 8Ryan Carniato argues that "elements are not components". What does he mean?

                Choose an answer to see the explanation.

              6. Question 6 of 8Which complaint from Rich Harris's 2019 list no longer holds?

                Choose an answer to see the explanation.

              7. Question 7 of 8In the React example, what does the paragraph say after you click the second star?

                Read the code, then predictPop out in the code editor (opens in a new tab)JSX
                import { useState } from "react";
                import "./tea-rating.js";
                
                export default function Review() {
                  const [stars, setStars] = useState(4);
                  return (
                    <section>
                      <h2>Review Green tea</h2>
                      <tea-rating value={stars} onrating-change={(event) => setStars(event.detail)} />
                      <p>React has {stars} stars in its state.</p>
                    </section>
                  );
                }

                Choose an answer to see the explanation.

              8. Question 8 of 8Do web components replace React?

                Choose an answer to see the explanation.

              Key takeaways

              • Use web components for parts that many apps, frameworks, or teams share: a rating, a widget, a design system.
              • Use a built-in element first. A tag's name doesn't give it a button's keyboard support or meaning.
              • A web component talks like any element: attributes and properties go in, and events come out. Every framework speaks that.
              • Design systems pick web components because browsers keep them working while frameworks change.
              • The case against is real: each component is a DOM element, attributes are strings, and server rendering and accessibility still take care.
              • Shadow DOM protects a component's inside. Light DOM lets the page style it, and shows before JavaScript runs.
              • Web components sit next to a framework. The framework runs the app, and the component is one tag in it.

              Remember the one-liner.
              Build a web component when many apps or frameworks share a part. Use plain HTML when it does the job, and let your framework run the app around it.

              Sources

              The facts and opinions on this page come from these standards, guides, posts, and data:

              Coming next: Your setup and the course project. Set up a folder, a dev server, and DevTools, and meet the tea shop UI kit you'll build in this course.

              CompleteFrontend Clear concepts. Working examples.