completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

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.

By the end, you can
  • 01
    Say what Lit addsName the parts Lit gives a custom element (reactive properties, html templates, and css styles) and the piece of the tea kit each one matches.
  • 02
    Write a first Lit componentExtend LitElement, register it with customElements.define() or @customElement, and give it an HTMLElementTagNameMap entry in TypeScript.
  • 03
    Tell Lit's packages apartKnow what lit, lit-html, @lit/reactive-element, and lit-element hold, and what the @lit and @lit-labs names 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:

Two badges drawn by LitPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Lines 1 to 3 are an import map (lesson 1.4). It says that the name lit means 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:

tea-badge.js: the badge as a LitElementJavaScript
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, and css.
  • Line 3 maps each kind of tea to its name.
  • Line 5 makes the badge a LitElement.
  • Line 6 declares one property, kind. reflect: true copies it to the kind attribute.
  • Lines 7 to 12 are the styles, in Lit's css tag.
  • Lines 14 to 16 draw the badge. render() returns an html template: 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.

Real-life analogyThe browser is the kitchen, and Lit is the prep station

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
The main idea

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.

The tea kit's pieces and Lit's
What you builtIn the tea kitIn 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:

The browser's own parts under a Lit badgePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 8 waits for the badge's first update. updateComplete is the same promise as ReactiveTea'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):

  • ReactiveElement handles reactive properties and attributes. It extends HTMLElement.
  • LitElement adds templates. It extends ReactiveElement.
Two columns of cards with arrows pointing down. The tea kit column: TeaBadge, then TeaElement, then ReactiveTea. The Lit column: TeaBadge, then LitElement, then ReactiveElement. Between the columns, the rows are labeled your component, the base class, and batches updates. Both columns end in one shared card at the bottom, HTMLElement, labeled the browser's class, shared by both.The tea kitLitTeaBadgeTeaBadgeyour componentTeaElementLitElementthe base classReactiveTeaReactiveElementbatches updatesHTMLElementthe browser's class, shared by both
Each arrow means extends. The kit's badge and Lit's badge climb the same three steps, and both end in the browser's own HTMLElement.

This page checks each step of the chain:

The badge's class chain, step by stepPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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() asks ReactiveElement for the render root, then notes where to draw (lines 144 to 153). ReactiveElement attaches a shadow root with mode: "open" and adopts the styles (reactive-element.ts, lines 1119 to 1130).
  • update() calls your render(), then ReactiveElement's update(). Then it hands the result to lit-html's render(), into the render root (lines 162 to 172).
  • connectedCallback() and disconnectedCallback() tell the template whether it's on the page (lines 194 to 221).
  • render() returns noChange, 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:

A Lit badge from plain DOM codePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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.

Real-life analogyA lamp with a standard plug

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:

  1. Write a class that extends LitElement.
  2. Give it a render() that returns an html template.
  3. 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:

tea-badge.ts: the badge with decorators and a tag map entryTypeScript
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 no define() at the end.
  • Line 8 is @property(). It declares kind, 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:

shop.ts: TypeScript knows the badge (an error on purpose)TypeScript
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.

Real-life analogyA translator at the counter

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
Two windows, one above the other. The top window, tea-badge.ts, holds two lines: @customElement with tea-badge, and @property with reflect true, then kind equals an empty string. An arrow labeled TypeScript points down to the second window, tea-badge.js, which holds three lines: TeaBadge equals __decorate, then customElement with tea-badge, then TeaBadge. A note under it says customElement() calls customElements.define().tea-badge.ts@customElement("tea-badge")@property({ reflect: true }) kind = "";TypeScripttea-badge.jsTeaBadge = __decorate([customElement("tea-badge")], TeaBadge);customElement() calls customElements.define()
You write the decorators. TypeScript turns them into plain calls, lines 22 to 24 of its output, and the browser runs those. Lit itself needs no such step.

Here is what TypeScript wrote for tea-badge.ts. The tea-badge.js tab holds its output, and the page runs it:

The browser runs TypeScript's outputPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 2 maps lit/ too, so lit/decorators.js loads 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 call property().
  • 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, then import { 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:

Playground: the badge by hand and with Lit
A badge that changes twicePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
A string of HTML, written on every change

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.

The page is the same in every choice. Only the tea-badge.js tab changes.
  • 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 kind twice 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: 2 and Same slot: false. The file is 39 lines.
  • By hand, the careful way: Renders: 2 and Same slot: true. The file is 41 lines.
  • Lit: Renders: 1 and Same 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.

Two halves. The left half is By hand, with innerHTML. Before the change, the cards b Green b and slot are faded and crossed out. An arrow points down to new cards, b Black b and slot, labeled new nodes, parsed again. The right half is Lit. Before the change, it has cards b, Green, and slot, and only Green is faded and crossed out. An arrow points down from Green to Black. The b and the slot stay, labeled same b and slot, new text.By hand, with innerHTML<b>Green</b><slot><b>Black</b><slot>new nodes, parsed againLit<b>Green<slot><b>Black<slot>same b and slot, new text
After two changes, the innerHTML badge has a new <b> and a new <slot>. Lit's badge keeps both, and changes only the text inside the <b>.
Real-life analogyA menu board with slide-in prices

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:

The badge three ways
QuestionBy hand, with innerHTMLBy hand, the careful wayLit
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:

Above a crate, the line import LitElement, html, css from lit. The crate is labeled lit 3.3.3. Inside it are three cards: lit-html, labeled 3.3.3; @lit/reactive-element, labeled 2.1.2; and lit-element, labeled 4.2.2.import { LitElement, html, css } from "lit"lit-html@lit/reactive-elementlit-element3.3.32.1.24.2.2lit 3.3.3
One import from 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:

One bundle, three version numbersPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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.

Real-life analogyA tea gift set

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:

lit-html on its own, rendered twicePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 3 takes html and render() 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:

Lit's packages
PackageWhat it gives youCan you use it on its own?
litEverything below, from one name: LitElement, html, css, render(), and more.Yes. It's the package to install.
lit-htmlThe templates: html, render(), and the directives.Yes, to render templates into any element.
@lit/reactive-elementReactiveElement, css, and the decorators.Yes, for a base class without templates.
lit-elementLitElement, which joins the two above.It works, but import it from lit instead.
@lit/context, @lit/task, and other @lit packagesExtras that have left Labs. They follow the same rules as lit.Yes, next to lit.
@lit-labs/signals, @lit-labs/ssr, and other Labs packagesExperiments, 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 LitElement the successor to PolymerElement. 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/context left 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:

A Lit badge inside the kit's tea cardPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Lines 4 to 8 are the kit's tea-currency, from lesson 19.4, around the kit's tea-card.
  • Line 6 puts a lit-badge in the card's notes. It's the Lit badge, with its own tag name: the kit already has a tea-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?

Kitchen or prep station?
  • 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
Try it yourself
0 of 8 correct

Sort each job by who does it: the browser, or Lit.

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

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 true and answered setAttribute().
  • "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, and customElements.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

Exercise 1 · Warm-upPredict how many times render() runs

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>

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

    Exercise 2 · Warm-upPredict a badge made in JavaScript

    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>

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

      Exercise 3 · PracticeFind why the badge shows its markup

      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>
      ResultLoading…

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

        Exercise 4 · PracticeWrite tea-label with Lit

        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>
        ResultLoading…

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

          Exercise 5 · ChallengeFind why the badge never draws

          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>
          ResultLoading…

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

            Exercise 6 · ChallengeRead the kit's currency from a Lit price

            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>
            ResultLoading…

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

              Check your understanding

              The why Lit quiz · 8 questionsScore: first tries count
              1. Question 1 of 8What does LitElement extend?

                Choose an answer to see the explanation.

              2. Question 2 of 8With the innerHTML badge, the button sets kind twice. What does the console print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              3. 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.

              4. 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.

              5. Question 5 of 8You only want html and render(), to fill in one part of a page. Which package do you need?

                Choose an answer to see the explanation.

              6. Question 6 of 8What does a package name that starts with @lit-labs/ tell you?

                Choose an answer to see the explanation.

              7. 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.

              8. 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:

              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.

              CompleteFrontend Clear concepts. Working examples.