Sitemap
Netanel Basal

Learn development with great articles

Follow publication

Lit & RxJS — Made for Each Other

--

Lit provides a simple way to build fast, lightweight web components.
Lit is at its core a boilerplate-killing component base class that provides reactive state, scoped styles, and a declarative template system that’s tiny, fast, and expressive.

In this article, we’ll learn how to use RxJS with Lit and how they work well together. Let’s first create a component so that we’ll have something to work with:

Note that the lit-file-generator package can handle this boilerplate work for you:

Let’s explore two ways to use observables in lit templates:

Custom Async Directive

The first way is to use a custom async directive:

The code is straightforward. In the render() method, we unsubscribe from the old one if the observable changes and subscribe to the new one. We update the template’s value by using the asynchronous setValue() API of the directive when the observable emits.

Finally, we unsubscribe when the directive is disconnected from the DOM. Let’s use it in our template:

When we need to use the value in the template directly, using a directive is convenient. However, we’ll need to take a different approach when we need to pass the value to other directives such as repeat or use it in the component instance.

Moving on to the second way, let’s create a reactive controller:

Reactive Controller

Reactive controllers can hook into a component’s reactive update cycle. A controller can bundle state and behavior related to a feature, making it reusable across multiple component definitions.

Let’s create an AsyncController that takes an observable, subscribes to it and exposes the value:

The controller takes a source observable and optional initial value. Upon a new emission, it updates the value property and requests an update to the host template.

The neat thing about lit is that it batch updates to maximize performance and efficiency. Setting multiple properties at once triggers only one update scheduled asynchronously at microtask timing.

Let’s use our controller:

Isn’t that neat? 🧙‍♀️. If you’re looking for a reactive state management to work with lit, I highly recommend checking out Elf:

Follow me on Medium or Twitter to read more about Angular and JS!

--

--

Netanel Basal
Netanel Basal
Netanel Basal
Netanel Basal

Written by Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.

No responses yet