Lit is a lightweight library for building web components without repeatedly writing the plumbing for property updates, rendering, and event handling. It stays close to web standards: a Lit component is still a custom element that can be used in a page. section 5.0
Listing 5.1 hello-world.ts
import { css, html, LitElement } from "lit";
import { customElement, property } from "lit/decorators.js";
@customElement("hello-world")
export class HelloWorld extends LitElement {
static styles = css` #1
:host {
color: blue;
}
`;
@property() name = "World";
render() {
return html`<p>Hello, ${this.name}!</p>`;
}
}
This small greeting component shows the basic pattern: extend LitElement, register a custom element, declare a reactive name property, and return an HTML template from render. section 5.2
In a template, expressions mark dynamic content. Changing a reactive property triggers rendering, but Lit updates only the DOM parts whose computed values changed. The @customElement decorator replaces a separate registration call; @property handles reactivity, while reflection to an HTML attribute can be requested explicitly. section 5.2
For larger components, Lit also reduces routine wiring:
- Use decorators for component configuration and reactive state; decorators are encouraged but optional. section 5.3 section 5.9
- Attach handlers in templates, then use lifecycle methods when an update needs additional work. section 5.6 section 5.9
- Keep components interoperable with forms, custom events, slots, and CSS custom properties. section 5.6
A radio group that changes other components
A Lit radio group renders its choices from property values, updates its form value when a choice changes, and emits a custom event. A page listens for that event and changes the color of two greeting components. The component remains responsible for its own rendering; the page handles the interaction between components. section 5.6
A sortable table extends the same approach: reactive properties hold its data and sort settings, template handlers respond to heading clicks, and willUpdate prepares sorted rows. Compared with an equivalent vanilla web component, Lit removes much of the manual property wiring and DOM updating. section 5.9
A common TypeScript starting point is the Vite lit-ts template, created with npm and run locally through Vite. Server-side rendering is also possible with additional Lit packages: the server supplies the first paint, and client-side code handles later interaction. The demonstrated SSR packages are under development and may change. section 5.1 section 11.4
