Store
@lit-material/storeStore
A tiny state store with no dependencies, for building whole applications with
lit-material, not just individual components. createStore has the exact
shape of Redux's four functions
(getState/dispatch/subscribe, driven by a pure reducer) and
works anywhere, including during SSR, since it has no dependency on the DOM or on Lit.
StoreController is the Lit reactive controller that subscribes a component to a store and
calls requestUpdate() only when the selected slice of state actually changes.
Install
npm install @lit-material/store
Usage
import { createStore, StoreController } from "@lit-material/store";
import { LitElement, html } from "lit";
interface CounterState {
count: number;
}
type CounterAction = { type: "increment" } | { type: "decrement" };
function counterReducer(state: CounterState, action: CounterAction): CounterState {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
}
}
// One store instance, shared by however many components need it.
export const counterStore = createStore(counterReducer, { count: 0 });
class MyCounter extends LitElement {
// Select the whole state...
private readonly store = new StoreController(this, counterStore);
// ...or a slice, so this host only re-renders when that slice changes:
// private readonly count = new StoreController(this, counterStore, (state) => state.count);
override render() {
return html`
<p>${this.store.value.count}</p>
<button @click=${() => counterStore.dispatch({ type: "increment" })}>+</button>
`;
}
}
API
createStore(reducer, preloadedState)
Returns a Store<S, A>:
| Method | Description |
|---|---|
getState(): S |
Current state. |
dispatch(action: A): A |
Runs the reducer, updates state, notifies subscribers, returns the action. |
subscribe(listener): () => void |
Registers a listener called after every dispatch; returns an unsubscribe function. |
new StoreController(host, store, selector?)
| Property | Description |
|---|---|
.value |
The currently selected state (whole state if no selector given). |
selector |
Optional (state: S) => V. The host renders again only when the selected value changes, not on every dispatch. |
Subscribes in hostConnected() and unsubscribes in hostDisconnected(), the
same reactive controller lifecycle that RippleController/FocusRingController in
@lit-material/core use.