Let’s create a simple counter application to demonstrate the core concepts.
1
Install TanStack Store
First, install the appropriate package for your framework:
npm install @tanstack/react-store
2
Create a Store
Create a store to manage your application state. Stores can be created inside or outside of components:
import { Store } from '@tanstack/react-store'// Create a store with initial stateexport const store = new Store({ dogs: 0, cats: 0,})
Stores can be instantiated outside of components and shared across your entire application.
3
Read Store State
Use the framework adapter’s hook/composable to read from the store. Only the specific data you select will trigger re-renders:
import { useStore } from '@tanstack/react-store'import { store } from './store'function Display({ animal }: { animal: 'dogs' | 'cats' }) { // This component only re-renders when state[animal] changes const count = useStore(store, (state) => state[animal]) return <div>{animal}: {count}</div>}
The selector function enables fine-grained subscriptions. Components only re-render when their selected data changes, not when any part of the store updates.
4
Update Store State
Update the store state using setState. Updates are immutable and trigger subscriptions:
function App() { return ( <div> <h1>How many of your friends like cats or dogs?</h1> <p> Press one of the buttons to add a counter of how many of your friends like cats or dogs </p> <Increment animal="dogs" /> <Display animal="dogs" /> <Increment animal="cats" /> <Display animal="cats" /> </div> )}
import { createStore } from '@tanstack/store'// Store with a valueconst countStore = createStore(0)// Store with an objectconst userStore = createStore({ name: 'John', age: 30,})
Batch multiple updates to trigger subscribers only once:
import { batch } from '@tanstack/store'const countStore = createStore(0)// Subscribers will only trigger once with the final valuebatch(() => { countStore.setState(() => 1) countStore.setState(() => 2)})console.log(countStore.state) // 2