Open History to see the last commit
1---
2title: Quick Start
3id: quick-start
4---
5β
6The basic Lit app example to get started with TanStack `lit-store`.
7β
8You can use `TanStackStoreSelector` in two ways:
9β
10- Trigger rerenders when a selected slice changes
11- Access the selected value directly through `.value`
12β
13```ts
14import { LitElement, html } from 'lit'
15import { customElement, property } from 'lit/decorators.js'
16import { TanStackStoreSelector, createStore } from '@tanstack/lit-store'
17β
18// You can instantiate a Store outside of Lit components too!
19export const store = createStore({
20 dogs: 0,
21 cats: 0,
22})
23β
24type Animal = 'dogs' | 'cats'
25β
26const updateState = (animal: Animal) => {
27 store.setState((state) => ({
28 ...state,
29 [animal]: state[animal] + 1,
30 }))
31}
32β
33@customElement('animal-display')
34export class AnimalDisplay extends LitElement {
35 @property({ type: String }) animal: Animal = 'dogs'
36β
37 // Subscribes only to `state[animal]`
38 counter = new TanStackStoreSelector(
39 this,
40 () => store,
41 (state) => state[this.animal],
42 )
43β
44 render() {
45 return html`
46 <div>
47 <p>
48 Using selector.value:
49 ${this.counter.value}
50 </p>
51β
52 <p>
53 Reading directly from store.state:
54 ${store.state[this.animal]}
55 </p>
56 </div>
57 `
58 }
59}
60β
61@customElement('animal-increment')
62export class AnimalIncrement extends LitElement {
63 @property({ type: String }) animal: Animal = 'dogs'
64β
65 render() {
66 return html`
67 <button @click=${() => updateState(this.animal)}>
68 My Friend Likes ${this.animal}
69 </button>
70 `
71 }
72}
73β
74@customElement('tanstack-store-demo')
75export class TanStackStoreDemo extends LitElement {
76 render() {
77 return html`
78 <div>
79 <h1>How many of your friends like cats or dogs?</h1>
80β
81 <p>
82 Press one of the buttons to increment how many of your friends
83 like cats or dogs.
84 </p>
85β
86 <animal-increment animal="dogs"></animal-increment>
87 <animal-display animal="dogs"></animal-display>
88β
89 <animal-increment animal="cats"></animal-increment>
90 <animal-display animal="cats"></animal-display>
91 </div>
92 `
93 }
94}
95```
96β
97`selector.value` returns the latest selected value and only updates when
98that specific selection changes.
99β
100Reading from `store.state` accesses the full store state directly. The
101component still rerenders because the selector subscription is active,
102but the rendered value itself comes from the store.
103β
104Then mount the root element in your HTML:
105β
106```html
107<tanstack-store-demo></tanstack-store-demo>
108<script type="module" src="/src/index.ts"></script>
109```