본문으로 건너뛰기

빠른 시작

TanStack lit-store를 시작하기 위한 기본 Lit 앱 예시입니다.

TanStackStoreSelector는 다음 두 가지 방식으로 사용할 수 있습니다.

  • 선택한 상태 조각이 변경될 때 다시 렌더링합니다
  • .value를 통해 선택한 값에 직접 접근합니다
import { LitElement, html } from 'lit'
import { customElement, property } from 'lit/decorators.js'
import { TanStackStoreSelector, createStore } from '@tanstack/lit-store'

// You can instantiate a Store outside of Lit components too!
export const store = createStore({
dogs: 0,
cats: 0,
})

type Animal = 'dogs' | 'cats'

const updateState = (animal: Animal) => {
store.setState((state) => ({
...state,
[animal]: state[animal] + 1,
}))
}

@customElement('animal-display')
export class AnimalDisplay extends LitElement {
@property({ type: String }) animal: Animal = 'dogs'

// Subscribes only to `state[animal]`
counter = new TanStackStoreSelector(
this,
() => store,
(state) => state[this.animal],
)

render() {
return html`
<div>
<p>
Using selector.value:
${this.counter.value}
</p>

<p>
Reading directly from store.state:
${store.state[this.animal]}
</p>
</div>
`
}
}

@customElement('animal-increment')
export class AnimalIncrement extends LitElement {
@property({ type: String }) animal: Animal = 'dogs'

render() {
return html`
<button @click=${() => updateState(this.animal)}>
My Friend Likes ${this.animal}
</button>
`
}
}

@customElement('tanstack-store-demo')
export class TanStackStoreDemo extends LitElement {
render() {
return html`
<div>
<h1>How many of your friends like cats or dogs?</h1>

<p>
Press one of the buttons to increment how many of your friends
like cats or dogs.
</p>

<animal-increment animal="dogs"></animal-increment>
<animal-display animal="dogs"></animal-display>

<animal-increment animal="cats"></animal-increment>
<animal-display animal="cats"></animal-display>
</div>
`
}
}

selector.value는 최근에 선택한 값을 반환하며 해당 선택 결과가 변경될 때만 업데이트됩니다.

store.state를 읽으면 전체 스토어 상태에 직접 접근합니다. 셀렉터 구독이 활성화되어 있으므로 컴포넌트는 계속 다시 렌더링되지만, 렌더링되는 값 자체는 스토어에서 가져옵니다.

그런 다음 HTML에 루트 엘리먼트를 마운트합니다.

<tanstack-store-demo></tanstack-store-demo>
<script type="module" src="/src/index.ts"></script>