Lit Explained: Web Components Without the Framework
Introduction
Frameworks come and go, but web components — custom elements, shadow DOM, HTML templates — are browser standards, supported everywhere, with no framework to outgrow. The catch has always been boilerplate: raw web components need a lot of ceremony for reactivity and templating. Lit, released in 2019 by Google, removes that ceremony: a tiny library (about 5KB) that adds reactive properties and declarative templates to standard web components, so you build framework-free components that work in any page, with any framework, forever.
Reactive properties and declarative templates
Lit's model is small and standards-based:
LitElement— a base class extendingHTMLElement, adding reactivity: declare a property, and Lit re-renders the component when it changes.- Reactive properties — decorated fields (or a static properties definition) that trigger updates on change, with attribute reflection for HTML attributes.
htmltemplates — tagged template literals that describe the DOM declaratively, with expressions for dynamic values and event bindings, efficiently updated in place.- Shadow DOM — styles and markup encapsulated per component by the platform itself, so a component's CSS never leaks.
A counter shows the whole model — a custom element, reactive state, and a template, in a few lines:
import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";
@customElement("my-counter")
class MyCounter extends LitElement {
@state() count = 0;
render() {
return html`
<button @click=${() => this.count++}>
Clicks: ${this.count}
</button>
`;
}
}
Use it anywhere with <my-counter></my-counter> — in a React app, a Vue app, plain HTML, or another framework's page, with no adapter. That portability is Lit's whole argument.
The honest trade
Lit's trade is ecosystem and ergonomics: fewer ready-made component libraries than React, and shadow DOM styling has its own learning curve (theming across shadow boundaries needs CSS custom properties). Server rendering exists but is younger than React's. The rule of thumb: Lit when building shareable, framework-agnostic components or design systems; a full framework when building an entire app with routing, state management, and a large ecosystem.
Takeaway
Lit is web components without the framework: reactive properties, declarative templates, and shadow DOM encapsulation, on browser standards, in about 5KB. It trades framework ecosystem for components that outlive frameworks — and for design systems, that longevity is the point.
Comments
Post a Comment