Open History to see the last commit
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```