Skip to content
Source
Sign inSign up
TanStack/store
Open History to see the last commit

quick-start.md

94 lines2.1 KB

1---
2title: Quick Start
3id: quick-start
4---
5​
6TanStack Store is, first and foremost, a framework-agnostic signals implementation.
7​
8It can be used with any of our framework adapters, but can also be used in vanilla JavaScript or TypeScript. It's currently used to power many of our library's internals.
9​
10## Store
11​
12You'll start by creating a new store instance, which is a wrapper around your data:
13​
14```typescript
15import { createStore } from '@tanstack/store';
16​
17const countStore = createStore(0);
18​
19console.log(countStore.state); // 0
20countStore.setState(() => 1);
21console.log(countStore.state); // 1
22```
23​
24This `Store` can then be used to track updates to your data:
25​
26```typescript
27const {unsubscribe} = countStore.subscribe(() => {
28 console.log('The count is now:', countStore.state);
29});
30​
31// Later, to cleanup
32unsubscribe();
33```
34​
35### Batch Updates
36​
37You can batch updates to a store by using the `batch` function:
38​
39```typescript
40import { batch } from '@tanstack/store';
41​
42// countStore.subscribers will only trigger once at the end with the final state
43batch(() => {
44 countStore.setState(() => 1);
45 countStore.setState(() => 2);
46});
47```
48​
49## Derived Stores
50​
51You can create derived stores that automatically update when their dependencies change:
52​
53```typescript
54const count = createStore(0);
55​
56const double = createStore(() => count.state * 2);
57​
58console.log(double.state); // 0
59count.setState(() => 5);
60console.log(double.state); // 10
61```
62​
63### Previous Derived Value
64​
65You can access the previous value of a derived computation by using the `prev` argument passed to the function:
66​
67```typescript
68const count = createStore(1);
69​
70const sum = createStore<number>((prev) => {
71 return count.state + (prev ?? 0);
72});
73​
74console.log(sum.state); // 1
75count.setState(() => 2);
76console.log(sum.state); // 3
77```
78​
79## Subscriptions
80​
81You can subscribe to store changes to perform side effects:
82​
83```typescript
84const count = createStore(0);
85​
86const {unsubscribe} = count.subscribe((state) => {
87 console.log('The count is now:', state);
88});
89​
90count.setState(() => 5); // Logs: "The count is now: 5"
91​
92// Later, to cleanup
93unsubscribe();
94```