Why Lit?
What is Lit? Learn what LitElement adds to web components, build a first Lit component in JavaScript and TypeScript, and compare it with one written by hand.
- 01Say what Lit addsName the parts Lit gives a custom element (reactive properties,
htmltemplates, andcssstyles) and the piece of the tea kit each one matches. - 02Write a first Lit componentExtend
LitElement, register it withcustomElements.define()or@customElement, and give it anHTMLElementTagNameMapentry in TypeScript. - 03Tell Lit's packages apartKnow what
lit,lit-html,@lit/reactive-element, andlit-elementhold, and what the@litand@lit-labsnames mean.
What is Lit?
Asha runs the Leaf and Kettle web shop. Over the last two modules, she built a toolkit by hand. It has a base class, a template tag, controllers, context, and tasks. Then Ravi joins the team. On his first day, he asks one question: "Why didn't you just use Lit?"
What would Lit have given her? And would her components still be the same kind of thing?
Lit is a small library for building web components. It gives your custom elements a base class with reactive properties, html templates that update only what changed, and shared styles. A Lit component is still a standard custom element, so it works in any page and any framework.
Here is the tea shop's badge, written with Lit:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><p>Assam <tea-badge kind="black">Strong</tea-badge></p><script type="module" src="./tea-badge.js"></script>- Lines 1 to 3 are an import map (lesson 1.4). It says that the name
litmeans Lit 3.3.3 on esm.sh, a server that hosts npm packages. - Lines 4 and 5 are two badges. Line 6 loads the tea-badge.js tab.
The tea-badge.js tab holds the whole component:
import { LitElement, html, css } from "lit";
const kinds = new Map([["green", "Green"], ["oolong", "Oolong"], ["black", "Black"]]);
export class TeaBadge extends LitElement {
static properties = { kind: { reflect: true } };
static styles = css`
:host { display: inline-block; padding: 0 6px; border-radius: 8px; background: dimgray; color: white; }
:host([kind="green"]) { background: darkgreen; }
:host([kind="oolong"]) { background: sienna; }
:host([kind="black"]) { background: black; }
`;
render() {
return html`<b>${kinds.get(this.kind) ?? ""}</b> <slot></slot>`;
}
}
customElements.define("tea-badge", TeaBadge);- Line 1 takes three things from Lit:
LitElement,html, andcss. - Line 3 maps each kind of tea to its name.
- Line 5 makes the badge a
LitElement. - Line 6 declares one property,
kind.reflect: truecopies it to thekindattribute. - Lines 7 to 12 are the styles, in Lit's
csstag. - Lines 14 to 16 draw the badge.
render()returns anhtmltemplate: the kind's name in bold, then a slot for the badge's own text. - Line 19 registers the tag, as for any custom element.
The result shows Green Organic and Black Strong. Each badge has its own color. There's no attribute callback, no getter, no setter, and no attachShadow(). Lit does those.
The tea shop's kitchen has a stove, a sink, and a kettle. Those stay the same, whoever cooks. Next to the stove is a prep station. Before the morning rush, someone washes and cuts what each order needs. The cook still uses the same stove. Each order just goes out faster.
- In real life: The kitchen, with its stove and its sink
- In JavaScript: The browser: custom elements, shadow DOM, and slots
- In real life: The prep station by the stove
- In JavaScript: Lit's base class, LitElement
- In real life: Vegetables washed and cut before the rush
- In JavaScript: Properties, templates, and styles, set up for you
- In real life: The same dish, served faster
- In JavaScript: The same custom element, written in fewer lines
Lit is a base class, not a new kind of element. It sets up what every component repeats: properties that redraw it, templates that write only what changed, and styles. The element it makes is the browser's own custom element.
Look at line 6 again. It's the declared attribute of lesson 19.2. Line 15 is the html tag of lesson 18.2. That's no accident. The toolkit you built has the same shape as Lit.
What does Lit add to web components?
Lit's docs name three things it adds to the standards: reactive properties, declarative templates, and scoped styles (Lit).
- A reactive property is a property that redraws the component when it changes.
- A declarative template describes what the component shows. You don't write the steps to change it.
- Scoped styles are CSS that stays inside the component.
You have built each one already. So here is a map, from your toolkit to Lit. Read each row across: what you built, its file in the kit, and Lit's name for it.
| What you built | In the tea kit | In Lit |
|---|---|---|
| Many changes joined into one update, in lesson 18.1. | ReactiveTea, in reactive.js. | ReactiveElement, from @lit/reactive-element. |
| A template that writes only the values that changed, in lesson 18.2. | html and render(), in html.js. | html and render(), from lit-html. |
| Lists that keep each row with its item, in lesson 18.3. | repeat(), in html.js. | The repeat directive, from lit/directives/repeat.js. |
A base class with styles, a template, and render(), in lesson 19.1. | TeaElement, in element.js. | LitElement, from lit-element. |
| Declared attributes, and a decorator for them, in lesson 19.2. | static attributes and @attribute(). | static properties and @property(). |
| Controllers that hook into the lifecycle, in lesson 19.3. | addController() on TeaElement. | addController() on ReactiveElement. |
| Signals that tell only their readers when they change, in lesson 18.5. | State, Computed, and effect(), in signals.js. | SignalWatcher, from @lit-labs/signals. |
| Context from an ancestor, in lesson 19.4. | context.js. | @lit/context. |
| Loading data with a status, in lesson 19.5. | TeaTask, in task.js. | Task, from @lit/task. |
Each row has its lesson: batching (18.1), templates (18.2), keys (18.3), a base class (19.1), declared attributes (19.2), controllers (19.3), signals (18.5), context (19.4), and tasks (19.5).
The first six rows are in the lit package. The last three are extra packages, which later lessons in this stage cover. Lit's docs put Lit at about 5 KB, minified and compressed (Lit).
What does Lit leave to the browser?
Everything else. Lit doesn't make its own kind of element. It calls the same browser APIs you call by hand. This page asks the badge about them:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><script type="module"> import { TeaBadge } from "./tea-badge.js"; const badge = document.querySelector("tea-badge"); await badge.updateComplete; console.log(`Registered with the browser: ${customElements.get("tea-badge") === TeaBadge}`); console.log(`Shadow root: ${badge.shadowRoot.mode}`); console.log(`Adopted sheets: ${badge.shadowRoot.adoptedStyleSheets.length}`); badge.kind = "oolong"; await badge.updateComplete; console.log(`Attribute: ${badge.getAttribute("kind")}`);</script>- Line 8 waits for the badge's first update.
updateCompleteis the same promise asReactiveTea's (lesson 18.1). - Line 9 asks the browser's registry which class owns the tag.
- Line 10 reads the shadow root's mode. Line 11 counts the sheets it adopted.
- Lines 12 and 13 set the property and wait. Line 14 reads the attribute.
It prints Registered with the browser: true, Shadow root: open, Adopted sheets: 1, and Attribute: oolong. The badge now shows Oolong Organic.
So the badge's class sits in the browser's own registry. Lit attached an open shadow root, and it handed its sheet to adoptedStyleSheets (lesson 11.5). Then it copied the property to the attribute. Every one of those is a browser API. Why it matters: what you learned in stages 2 to 7 still holds in Lit. Lit only calls it for you.
What is LitElement?
LitElement is Lit's base class. Your component extends it, as the kit's components extend TeaElement (lesson 19.1). Lit's docs describe two layers (Lit):
ReactiveElementhandles reactive properties and attributes. It extendsHTMLElement.LitElementadds templates. It extendsReactiveElement.
HTMLElement.This page checks each step of the chain:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><script type="module"> import { LitElement, ReactiveElement } from "lit"; import { TeaBadge } from "./tea-badge.js"; const parent = (Class) => Object.getPrototypeOf(Class); console.log(`TeaBadge extends LitElement: ${parent(TeaBadge) === LitElement}`); console.log(`LitElement extends ReactiveElement: ${parent(LitElement) === ReactiveElement}`); console.log(`ReactiveElement extends HTMLElement: ${parent(ReactiveElement) === HTMLElement}`); console.log(`The badge is an HTMLElement: ${document.querySelector("tea-badge") instanceof HTMLElement}`);</script>- Line 6 takes both base classes from
lit. - Line 8 finds a class's parent.
Object.getPrototypeOf()on a class gives the class it extends. - Lines 9 to 11 check three steps. Line 12 checks the badge itself with
instanceof.
All four lines end in true: TeaBadge extends LitElement: true, up to The badge is an HTMLElement: true.
How thin is LitElement?
Very. Its whole class is lines 130 to 233 of lit-element.ts at Lit 3.3.3, and most of those are comments (Lit). It does four things:
createRenderRoot()asksReactiveElementfor the render root, then notes where to draw (lines 144 to 153).ReactiveElementattaches a shadow root withmode: "open"and adopts the styles (reactive-element.ts, lines 1119 to 1130).update()calls yourrender(), thenReactiveElement'supdate(). Then it hands the result to lit-html'srender(), into the render root (lines 162 to 172).connectedCallback()anddisconnectedCallback()tell the template whether it's on the page (lines 194 to 221).render()returnsnoChange, which draws nothing, until you replace it (lines 230 to 232).
TeaElement's update() did the same: it called render() and handed the result to html.js (lesson 19.3). Both classes are glue between a batching base class and a template library.
Is a Lit component a real HTML element?
Yes. "Every Lit component is a standard web component," Lit's docs say (Lit). So plain DOM code can use it. This page's script has no framework and no Lit code:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p id="shelf"></p><script type="module"> import "./tea-badge.js"; const shelf = document.querySelector("#shelf"); shelf.innerHTML = `Sencha <tea-badge kind="green">Organic</tea-badge>`; const badge = shelf.querySelector("tea-badge"); badge.addEventListener("click", () => badge.setAttribute("kind", "black")); console.log(badge.localName, badge instanceof HTMLElement);</script>- Line 8 writes the badge as a string of HTML, the way a CMS or a framework might.
- Line 10 adds a click listener that calls
setAttribute(). - Line 11 prints the tag's name and checks
instanceof HTMLElement.
It prints tea-badge true, and the badge shows Green Organic. Click it, and it shows Black Organic.
Asha buys a lamp for the shop. She doesn't ask who made it. She only checks that it has a standard plug. Then it works in every socket in the shop, in the kitchen and at the counter.
- In real life: The standard plug
- In JavaScript: The custom elements standard
- In real life: The lamp's maker
- In JavaScript: Lit, or your own toolkit
- In real life: Any socket in the house
- In JavaScript: Plain HTML, React, Vue, or Angular
- In real life: The lamp lights up
- In JavaScript: The badge upgrades and draws
Frameworks see a Lit component as one more custom element. Lesson 2.5 showed how React, Vue, Angular, and Svelte use custom elements.
How do you create a Lit component?
Three steps, for any Lit component:
- Write a class that extends
LitElement. - Give it a
render()that returns anhtmltemplate. - Register it with a tag name.
The badge did all three in JavaScript. Its last line called customElements.define(), the browser's own registry. In TypeScript, Lit offers a shorter way: the @customElement decorator. Lit's docs call it shorthand for customElements.define() (Lit).
A first Lit component in TypeScript
A decorator is a function you write after an @ sign. It runs once, when the class is made (decorators). Here is the badge with Lit's two most common ones:
import { LitElement, html } from "lit";
import { customElement, property } from "lit/decorators.js";
const kinds = new Map([["green", "Green"], ["oolong", "Oolong"], ["black", "Black"]]);
@customElement("tea-badge")
export class TeaBadge extends LitElement {
@property({ reflect: true }) kind = "";
render() {
return html`<b>${kinds.get(this.kind) ?? ""}</b> <slot></slot>`;
}
}
declare global {
interface HTMLElementTagNameMap {
"tea-badge": TeaBadge;
}
}- Line 2 takes the decorators from
lit/decorators.js. - Line 6 is
@customElement("tea-badge"). It registers the class, so there's nodefine()at the end. - Line 8 is
@property(). It declareskind, with an empty string to start. - Lines 15 to 19 add the tag to
HTMLElementTagNameMap.
HTMLElementTagNameMap is TypeScript's list of tag names and their classes. It's how TypeScript knows that createElement("img") gives an image. Lit's docs recommend an entry for every element (Lit). With it, TypeScript checks your page's code:
import "./tea-badge.js";
const badge = document.createElement("tea-badge");
badge.kind = "oolong";
badge.kind = 5;On line 3, TypeScript knows that badge is a TeaBadge. Line 4 is fine. Line 5 is an error on purpose: Type 'number' is not assignable to type 'string'. That means you put a number where the badge wants text. Without the map entry, badge would be a plain HTMLElement, and line 4 would be an error too.
Do decorators need a build step?
Yes. No browser runs decorators yet, and Chrome refuses the @ sign (lesson 19.2). Lit's docs say you need a compiler, such as TypeScript or Babel (Lit). For TypeScript, they recommend two settings: experimentalDecorators: true and useDefineForClassFields: false. Lesson 19.2 showed why the second one matters.
A visitor orders tea in a language the cashier doesn't speak. A translator stands beside them and says the order again, in the cashier's words. The tea is the same. Only the words changed on the way.
- In real life: The visitor's own words
- In JavaScript: TypeScript with decorators
- In real life: The translator
- In JavaScript: The TypeScript compiler
- In real life: The cashier, who knows one language
- In JavaScript: The browser
- In real life: The same order, rung up
- In JavaScript: The same customElements.define() call
Here is what TypeScript wrote for tea-badge.ts. The tea-badge.js tab holds its output, and the page runs it:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><script type="module" src="./tea-badge.js"></script>- Line 2 maps
lit/too, solit/decorators.jsloads from the same place. - In the tea-badge.js tab, lines 1 to 6 are TypeScript's helper,
__decorate. - Line 13 sets the starting
kind. Lines 19 to 21 callproperty(). - Lines 22 to 24 call
customElement("tea-badge")on the class.
The badge shows Green Organic, with no colors: this version has no styles. And customElement() is short. It calls customElements.define() (custom-element.ts, lines 46 to 62).
Lit itself needs no compiler. Its docs say you don't need any Lit-specific compilers or tools (Lit). Every JavaScript page in this lesson loads Lit from esm.sh, with no build at all.
Where do you start a Lit project?
Lit's Getting Started page lists the ways in (Lit):
- The Lit Playground, in the browser, with nothing to install.
npm i lit, thenimport { LitElement, html } from "lit".- A single-file bundle from a CDN, which the packages section loads.
- Starter kits for a component in JavaScript or TypeScript.
This lesson's pages use a fifth way: an import map that points lit at esm.sh.
How does Lit compare with a web component written by hand?
Here is the same badge three ways. The page is the same each time. Only its tea-badge.js tab changes. Choose a version, then press Oolong, then black:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><button id="change">Oolong, then black</button><script type="module"> import { TeaBadge } from "./tea-badge.js"; const badge = document.querySelector("tea-badge"); const draw = TeaBadge.prototype.render; let renders = 0; TeaBadge.prototype.render = function () { renders++; return draw.call(this); }; document.querySelector("#change").addEventListener("click", async () => { const slot = badge.shadowRoot.querySelector("slot"); renders = 0; badge.kind = "oolong"; badge.kind = "black"; await badge.updateComplete; console.log(`Renders: ${renders}`); console.log(`Same slot: ${badge.shadowRoot.querySelector("slot") === slot}`); });</script>Press Oolong, then black. It prints Renders: 2 and Same slot: false. Each change ran render(), and each render() threw the old nodes away and parsed new ones.
- Lines 9 to 14 wrap the class's
render(), so the page can count its calls. Only this page does that, to measure. - Line 16 keeps the slot that's in the shadow root before the changes.
- Lines 18 and 19 change
kindtwice in a row. - Line 20 waits for Lit's update. The hand-written badges have no
updateComplete, so it waits for nothing. - Line 21 prints the count. Line 22 checks whether the slot is still the same node.
- By hand, with innerHTML:
Renders: 2andSame slot: false. The file is 39 lines. - By hand, the careful way:
Renders: 2andSame slot: true. The file is 41 lines. - Lit:
Renders: 1andSame slot: true. The file is 19 lines.
All three badges end up showing Black Organic. What differs is the work it took, and who wrote it.
<b> and a new <slot>. Lit's badge keeps both, and changes only the text inside the <b>.The tea shop's menu is on a board. On one board, changing a price means wiping it clean and writing every line again. On a better board, each price is a tile. You slide out one tile and slide in a new one. If two prices change, you wait a moment and swap them together.
- In real life: Wiping the whole board
- In JavaScript: Setting innerHTML
- In real life: Writing every line again
- In JavaScript: Parsing a new b and a new slot
- In real life: Sliding in one new tile
- In JavaScript: lit-html writing one text
- In real life: Waiting until both changes are in
- In JavaScript: Lit joining two changes into one update
Read each row across, one version at a time:
| Question | By hand, with innerHTML | By hand, the careful way | Lit |
|---|---|---|---|
| How many lines is tea-badge.js? | 39. | 41. | 19. |
How many times does render() run for two changes? | 2: once for each change. | 2: once for each change. | 1: both changes join one update. |
| Is the slot the same node after the changes? | No. Every render parses new nodes. | Yes. Only a text node's data changes. | Yes. lit-html writes only the kind's text. |
| Who writes the attribute and the property? | You: observedAttributes, a getter, and a setter. | You, the same way. | Lit, from one line: static properties. |
The innerHTML version is easy to write, but it throws nodes away. A thrown-away node loses focus and typed text (lesson 19.1). The careful version keeps them, but it's the longest. Lit gives you the careful version's updates in fewer than half its lines. That's what you'd get from your own toolkit, too: TeaElement and html.js do the same work.
Lit's own unfinished tutorial makes the same trade. Its hand-written rating element has 101 lines, and the Lit version has 75 (Lit).
What are lit, lit-html, and lit-element?
Lit is one name for a few packages. The one you install is lit. It holds almost no code of its own:
- Its main file re-exports
lit-element(index.ts, line 13). lit-elementholdsLitElement, and re-exports everything from@lit/reactive-elementandlit-html(lit-element.ts, lines 49 to 52).- Those three are the
litpackage's only dependencies (package.json, lines 346 to 350).
lit brings three packages, each with its own version number. The bundle page printed the same three.Each of the three has its own version number. Each one also adds its number to a list on globalThis when it loads (lit-html.ts, line 2210). So a page can ask. This one loads Lit's single-file bundle from jsDelivr:
<script type="module"> import "https://cdn.jsdelivr.net/gh/lit/dist@3.3.3/core/lit-core.min.js"; console.log(`lit-html ${globalThis.litHtmlVersions}`); console.log(`@lit/reactive-element ${globalThis.reactiveElementVersions}`); console.log(`lit-element ${globalThis.litElementVersions}`);</script>- Line 2 loads the bundle. It's one file, with no imports of its own.
- Lines 3 to 5 print the list each package added itself to.
It prints lit-html 3.3.3, @lit/reactive-element 2.1.2, and lit-element 4.2.2. Three packages, inside one file of Lit 3.3.3. The bundle is 15,734 bytes before compression.
Leaf and Kettle sells a gift set: a teapot, two cups, and a tray, in one box. Most people buy the box. But the teapot is sold on its own too. Next to the boxes, a tasting shelf holds new flavors. They may change before they join the menu.
- In real life: The gift set, in one box
- In JavaScript: The lit package
- In real life: The teapot, also sold on its own
- In JavaScript: lit-html
- In real life: The cups and the tray
- In JavaScript: @lit/reactive-element and lit-element
- In real life: A new flavor on the tasting shelf
- In JavaScript: A @lit-labs package
Can you use lit-html on its own?
Yes. Lit's docs say lit-html works outside the component model, anywhere you need to render HTML (Lit). Lesson 18.2 put it next to your html.js. Here it fills one paragraph, with no component:
<p id="order"></p><script type="module"> import { html, render } from "https://esm.sh/lit-html@3.3.3"; const order = document.querySelector("#order"); const line = (tea) => html`Your tea: <b>${tea}</b>`; render(line("Sencha"), order); const bold = order.querySelector("b"); render(line("Oolong"), order); console.log(order.textContent); console.log(`Same b: ${order.querySelector("b") === bold}`);</script>- Line 3 takes
htmlandrender()from lit-html alone. - Line 5 is a template function. Lines 6 and 8 render it twice, with two teas.
- Line 7 keeps the first
<b>. Line 10 compares it with the one after the second render.
It prints Your tea: Oolong and Same b: true. The second render changed only the text.
What do @lit and @lit-labs mean?
Lit's other packages have two kinds of names (Lit). A package under @lit-labs/ is still being shaped: breaking changes come more often. When it's ready, it graduates and is published under @lit/. @lit-labs/task became @lit/task, which lesson 19.5 used. Read each row across:
| Package | What it gives you | Can you use it on its own? |
|---|---|---|
lit | Everything below, from one name: LitElement, html, css, render(), and more. | Yes. It's the package to install. |
lit-html | The templates: html, render(), and the directives. | Yes, to render templates into any element. |
@lit/reactive-element | ReactiveElement, css, and the decorators. | Yes, for a base class without templates. |
lit-element | LitElement, which joins the two above. | It works, but import it from lit instead. |
@lit/context, @lit/task, and other @lit packages | Extras that have left Labs. They follow the same rules as lit. | Yes, next to lit. |
@lit-labs/signals, @lit-labs/ssr, and other Labs packages | Experiments, still being shaped. | Yes, but expect breaking changes more often. |
Where did Lit come from?
- It started at Google, after Polymer. At Google I/O 2018, the Polymer team named
LitElementthe successor toPolymerElement. Polymer's README still tells new projects to use LitElement (Polymer). - lit-html and LitElement were separate packages, with separate docs. Lit 2.0, in 2021, joined them into one product, Lit, and one package,
lit(Lit). - Lit 3.0 came out on October 10, 2023. It dropped Internet Explorer 11, published its code as ES2021, and added standard decorators.
@lit/react,@lit/task, and@lit/contextleft Labs that day (Lit). - On October 14, 2025, Lit joined the OpenJS Foundation, the non-profit home of Node.js and webpack (Lit).
So old tutorials may write import { LitElement } from "lit-element". That was LitElement's own package before Lit 2. Lit's upgrade guide says to import from lit instead (Lit). Lit 3.3.3 is the newest release.
Is Lit a Google project?
Not anymore. Google gave Lit and its assets to the OpenJS Foundation (OpenJS Foundation). That means its code, its docs, its website, and its name. A Technical Steering Committee now runs it. Its first members work at Google, Adobe, and Reddit, and two are independent (Lit). Why it matters: Lit's future no longer hangs on one company's plans.
Using a Lit badge in the tea kit
Asha doesn't have to choose. Lit components and the kit's components are all custom elements, so they share a page. Here the kit's card holds a Lit badge in its notes:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-currency code="EUR"> <tea-card name="Sencha" price="4"> <p>Grassy and sweet. <lit-badge kind="green">Organic</lit-badge></p> </tea-card></tea-currency><script type="module"> import "./tea-kit/index.js"; import "./lit-badge.js";</script>- Lines 4 to 8 are the kit's
tea-currency, from lesson 19.4, around the kit'stea-card. - Line 6 puts a
lit-badgein the card's notes. It's the Lit badge, with its own tag name: the kit already has atea-badge. - Line 10 loads the kit. Line 11 loads the Lit badge, in the lit-badge.js tab.
The card shows Sencha and Price: 4 EUR, and its notes hold the badge, Green Organic. The card sees its notes and turns on its has-notes state, as it does for any notes. Nothing in the kit knows the badge came from Lit.
Real products mix Lit with other code the same way. Lit's OpenJS post lists Photoshop and Illustrator on the web, Reddit, MDN, Chrome DevTools, Firefox's own interface, Home Assistant, and Web Awesome among its users (Lit). Firefox's base class extends LitElement, as lesson 19.1 showed.
Now sort the jobs. Which ones does the browser do, and which does Lit set up?
- Registering the tag tea-badge
- Making the shadow root
- Showing the badge's own text, Organic, through a slot
- Sharing one stylesheet between every badge
- Turning one line, static properties, into a property and an attribute
- Drawing once for two changes in a row
- Writing only the kind's text when it changes
- Turning CSS text into a sheet, once for the class
Sort each job by who does it: the browser, or Lit.
Common mix-ups
- "Lit is a Google project." No. Google gave it to the OpenJS Foundation in 2025. A committee with members from several companies runs it.
- "Lit components only work in Lit apps." No. A Lit badge from plain innerHTML printed
tea-badge trueand answeredsetAttribute(). - "Lit needs a compiler." No. Every JavaScript page here loaded Lit from esm.sh, with no build. Only decorators need TypeScript or Babel.
- "Lit re-renders the whole component on every change." No. The slot stayed the same node, and two changes made one render.
- "Lit replaces the browser's custom elements." No. It calls
attachShadow(),adoptedStyleSheets, andcustomElements.define(), as you do. - "Import LitElement from lit-element." No. That's from before Lit 2. Import from
lit. - "Polymer and Lit are the same thing." No.
<dom-module>,{{ }}bindings, and HTML Imports are Polymer. Polymer stopped at 3.5.2, and its README sends new projects to LitElement.
Practice exercises
The Lit badge's button sets three kinds in a row. What does the console print when you press Three kinds?
<script type="importmap">
{ "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
</script>
<p>Sencha <tea-badge kind="green">Organic</tea-badge></p>
<button id="change">Three kinds</button>
<script type="module">
import { TeaBadge } from "./tea-badge.js";
const badge = document.querySelector("tea-badge");
const draw = TeaBadge.prototype.render;
let renders = 0;
TeaBadge.prototype.render = function () {
renders++;
return draw.call(this);
};
document.querySelector("#change").addEventListener("click", async () => {
renders = 0;
badge.kind = "oolong";
badge.kind = "black";
badge.kind = "green";
await badge.updateComplete;
console.log(`Renders: ${renders}`);
});
</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><button id="change">Three kinds</button><script type="module"> import { TeaBadge } from "./tea-badge.js"; const badge = document.querySelector("tea-badge"); const draw = TeaBadge.prototype.render; let renders = 0; TeaBadge.prototype.render = function () { renders++; return draw.call(this); }; document.querySelector("#change").addEventListener("click", async () => { renders = 0; badge.kind = "oolong"; badge.kind = "black"; badge.kind = "green"; await badge.updateComplete; console.log(`Renders: ${renders}`); });</script>It prints Renders: 1. The three changes join one update, so render() runs once. The badge ends on green, the kind it started with, but it still draws once: the property changed three times on the way.
What does the new badge show?
<script type="importmap">
{ "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
</script>
<p id="shelf">Milk oolong </p>
<script type="module">
import "./tea-badge.js";
const badge = document.createElement("tea-badge");
badge.kind = "oolong";
badge.textContent = "Rare";
document.querySelector("#shelf").append(badge);
</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p id="shelf">Milk oolong </p><script type="module"> import "./tea-badge.js"; const badge = document.createElement("tea-badge"); badge.kind = "oolong"; badge.textContent = "Rare"; document.querySelector("#shelf").append(badge);</script>The badge shows Oolong Rare. createElement() runs the badge's constructor. Line 8 sets the property, and line 9 sets the text the slot shows. Lit draws once the badge joins the page, on line 10.
The badge shows <b>Green</b> <slot></slot> as text. Fix the tea-badge.js tab. What does the badge show then?
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><script type="module" src="./tea-badge.js"></script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><script type="module" src="./tea-badge.js"></script>Only line 15 of the tea-badge.js tab changes: the template gets its html tag. Without it, render() returns a plain string, and Lit draws a string as text, so the badge showed <b>Green</b> <slot></slot>. With html, Lit makes real nodes, and the badge shows Green Organic.
The tea-label.js tab is empty. Write tea-label as a LitElement. What does the page show after you press Brew longer?
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-label name="Green tea" minutes="3"></tea-label><button id="longer">Brew longer</button><script type="module"> import "./tea-label.js"; const label = document.querySelector("tea-label"); document.querySelector("#longer").addEventListener("click", () => { label.minutes = 4; });</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-label name="Green tea" minutes="3"></tea-label><button id="longer">Brew longer</button><script type="module"> import "./tea-label.js"; const label = document.querySelector("tea-label"); document.querySelector("#longer").addEventListener("click", () => { label.minutes = 4; });</script>Only the tea-label.js tab changes. It declares two properties, and render() writes them into one line. The page shows Green tea: brew for 3 minutes. Brew longer sets minutes to 4, Lit updates, and it shows Green tea: brew for 4 minutes.
The console prints A green badge joined the page, but the badge shows only Organic, with no color. Fix the tea-badge.js tab. What does the badge show then?
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><script type="module" src="./tea-badge.js"></script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><script type="module" src="./tea-badge.js"></script>Only the tea-badge.js tab changes: connectedCallback() calls super.connectedCallback() first. Without it, ReactiveElement never made the shadow root or allowed updates, so only the plain text Organic showed. Now the badge shows Green Organic, and the console still prints A green badge joined the page.
lit-price shows Price: 4, with no currency. Make it read the currency with the kit's own ContextConsumer, from lesson 19.4. What does it show after you press Pounds?
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-currency code="EUR"> <p><lit-price amount="4"></lit-price></p></tea-currency><button id="pounds">Pounds</button><script type="module"> import "./tea-kit/index.js"; import "./lit-price.js"; document.querySelector("#pounds").addEventListener("click", () => { document.querySelector("tea-currency").code = "GBP"; });</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-currency code="EUR"> <p><lit-price amount="4"></lit-price></p></tea-currency><button id="pounds">Pounds</button><script type="module"> import "./tea-kit/index.js"; import "./lit-price.js"; document.querySelector("#pounds").addEventListener("click", () => { document.querySelector("tea-currency").code = "GBP"; });</script>Only the lit-price.js tab changes. The kit's ContextConsumer adds itself to the Lit element, asks the nearest tea-currency when it connects, and asks for an update with each answer. It shows Price: 4 EUR, and after Pounds, Price: 4 GBP. Your toolkit's controller runs on Lit, because both hosts have the same four members.
Check your understanding
Question 1 of 8What does
LitElementextend?Choose an answer to see the explanation.
Question 2 of 8With the innerHTML badge, the button sets
kindtwice. What does the console print?Read the code, then predict<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } } </script> <p>Sencha <tea-badge kind="green">Organic</tea-badge></p> <button id="change">Oolong, then black</button> <script type="module"> import { TeaBadge } from "./tea-badge.js"; const badge = document.querySelector("tea-badge"); const draw = TeaBadge.prototype.render; let renders = 0; TeaBadge.prototype.render = function () { renders++; return draw.call(this); }; document.querySelector("#change").addEventListener("click", async () => { const slot = badge.shadowRoot.querySelector("slot"); renders = 0; badge.kind = "oolong"; badge.kind = "black"; await badge.updateComplete; console.log(`Renders: ${renders}`); console.log(`Same slot: ${badge.shadowRoot.querySelector("slot") === slot}`); }); </script>Choose an answer to see the explanation.
Question 3 of 8Which part of a TypeScript Lit component needs a compiler before the browser can run it?
Choose an answer to see the explanation.
Question 4 of 8A Lit badge is put on a page with no framework, through innerHTML. What happens?
Choose an answer to see the explanation.
Question 5 of 8You only want
htmlandrender(), to fill in one part of a page. Which package do you need?Choose an answer to see the explanation.
Question 6 of 8What does a package name that starts with
@lit-labs/tell you?Choose an answer to see the explanation.
Question 7 of 8An old tutorial writes
import { LitElement, html } from "lit-element". What do you write today?Choose an answer to see the explanation.
Question 8 of 8Who looks after Lit today?
Choose an answer to see the explanation.
Key takeaways
- Lit is a small library for web components: a base class, html templates, and css styles.
- A Lit component is a standard custom element. It works in plain HTML and in any framework.
- LitElement extends ReactiveElement, which extends the browser's HTMLElement.
- Each part matches a piece you built: ReactiveTea, html.js, TeaElement, declared attributes, controllers, context, and tasks.
- Register a Lit component with customElements.define(), or with @customElement in TypeScript. Add an HTMLElementTagNameMap entry for TypeScript.
- Decorators need a compiler. Lit itself doesn't.
- Lit joins changes into one update and writes only what changed, in fewer than half the careful badge's lines.
- Install
lit. It brings lit-html, @lit/reactive-element, and lit-element. @lit-labs packages are experiments. - Lit belongs to the OpenJS Foundation now, not Google alone.
Remember the one-liner.
Lit is the prep station, not a new kitchen: a base class that sets up your custom elements, which stay the browser's own.
Sources
The facts on this page come from these docs, posts, and source files:
- What is Lit?, Lit.
- Defining a component, Lit.
- lit-element.ts, at lit 3.3.3, Lit.
- reactive-element.ts, at lit 3.3.3, Lit.
- Decorators, Lit.
- custom-element.ts, at lit 3.3.3, Lit.
- Tools and workflows overview, Lit.
- Getting Started, Lit.
- From Web Component to Lit Element, an unpublished tutorial, Lit.
- index.ts of the lit package, at 3.3.3, Lit.
- package.json of the lit package, at 3.3.3, Lit.
- lit-html.ts, at lit 3.3.3, Lit.
- Using lit-html standalone, Lit.
- Lit Labs, Lit.
- Lit 2.0: Meet Lit, all over again!, Gray Norton, Lit.
- Lit 2 upgrade guide: update packages and import paths, Lit.
- Lit Launch Day: Lit 3.0, Labs graduations, a compiler and more!, Lit.
- Lit is Joining the OpenJS Foundation!, Lit.
- Lit Project Moves to OpenJS Foundation, OpenJS Foundation.
- Polymer's README, at v3.5.2, Polymer.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data.
Coming next: Reactive properties in Lit, the next lesson of the Lit stage. After it, the stage covers Lit's templates, styles, events, update lifecycle, directives, and signals, one lesson each. Tagged templates started in the JavaScript course: template literals.