본문으로 건너뛰기

빠른 시작

TanStack Store는 무엇보다 프레임워크에 구애받지 않는 시그널 구현체입니다.

모든 프레임워크 어댑터와 함께 사용할 수 있으며, 순수 JavaScript 또는 TypeScript에서도 사용할 수 있습니다. 현재 여러 TanStack 라이브러리의 내부 기능을 구동하는 데 사용됩니다.

스토어

먼저 데이터를 감싸는 새 스토어 인스턴스를 생성합니다.

import { createStore } from '@tanstack/store';

const countStore = createStore(0);

console.log(countStore.state); // 0
countStore.setState(() => 1);
console.log(countStore.state); // 1

이어서 이 Store를 사용해 데이터 업데이트를 추적할 수 있습니다.

const {unsubscribe} = countStore.subscribe(() => {
console.log('The count is now:', countStore.state);
});

// Later, to cleanup
unsubscribe();

업데이트 배칭

batch 함수를 사용하면 스토어 업데이트를 배칭할 수 있습니다.

import { batch } from '@tanstack/store';

// countStore.subscribers will only trigger once at the end with the final state
batch(() => {
countStore.setState(() => 1);
countStore.setState(() => 2);
});

파생 스토어

의존성이 변경될 때 자동으로 업데이트되는 파생 스토어를 생성할 수 있습니다.

const count = createStore(0);

const double = createStore(() => count.state * 2);

console.log(double.state); // 0
count.setState(() => 5);
console.log(double.state); // 10

이전 파생 값

함수에 전달되는 prev 인수를 사용하면 파생 연산의 이전 값에 접근할 수 있습니다.

const count = createStore(1);

const sum = createStore<number>((prev) => {
return count.state + (prev ?? 0);
});

console.log(sum.state); // 1
count.setState(() => 2);
console.log(sum.state); // 3

구독

스토어 변경을 구독해 사이드 이펙트를 수행할 수 있습니다.

const count = createStore(0);

const {unsubscribe} = count.subscribe((state) => {
console.log('The count is now:', state);
});

count.setState(() => 5); // Logs: "The count is now: 5"

// Later, to cleanup
unsubscribe();