Skip to content

🏪 A simple state management library for Lit components

License

Notifications You must be signed in to change notification settings

Julien-R44/lit-valtio-state

Repository files navigation

🏪 A simple state management library for Lit, built on top of valtio.

Installation

pnpm add @julr/lit-valtio-state

Usage

First you have to define a state, eg. in stores/app.ts :

import { defineState } from '@julr/lit-valtio-state'

export const appState = defineState({
  count: 0,
  name: 'John Doe'
})

Then you can simply use it in your components as follows :

import { LitElement, html } from 'lit'
import { customElement } from 'lit/decorators.js'
import { useState } from '@julr/lit-valtio-state'
import { appState } from '@/stores/app'

@customElement('my-lit-component')
export class MyLitComponent extends LitElement {
  private state = useState(this, appState)

  render() {
    return html`
      <div>
        <h1>${this.state.name}</h1>
        <p>${this.state.count}</p>
        <button @click=${() => this.state.count++}>Increment</button>
      </div>
    `
  }
}

How it works ?

This is made possible by Javascript proxies and Lit controllers

Basically, the state is a proxy, and the useState will create a Lit controller that will subscribe to the state changes. When a change is made, we will ask the host of the controller (so your Lit component), to make a new rendering.

License

MIT License © 2022 Julien Ripouteau