@tanstack/react-store package, which uses React’s useSyncExternalStore hook for optimal performance and automatic re-rendering.
Installation
Install the React adapter package:The
@tanstack/react-store package re-exports everything from @tanstack/store, so you only need to install the React package.Basic Usage
The primary way to use TanStack Store in React is through theuseStore hook:
The useStore Hook
TheuseStore hook subscribes your component to store updates and automatically triggers re-renders when selected state changes.
Signature
Parameters
store- The store instance to subscribe toselector- A function that selects which part of the state you needcompare- (Optional) A custom equality function to determine if the selected value has changed. Defaults toObject.is
Selector Optimization
The selector function allows you to subscribe to only the parts of state you need. Your component will only re-render when the selected value changes:Custom Equality Functions
For complex state selections, you can provide a custom equality function to prevent unnecessary re-renders:Shallow Equality
The package exports ashallow utility for shallow object comparison:
shallow function works with:
- Plain objects
- Maps
- Sets
- Dates
- Symbol keys
Complete Example: Todo App
Here’s a complete example demonstrating store creation, updates, and React integration:React-Specific Considerations
Concurrent Features
The React adapter usesuseSyncExternalStore under the hood, which means it’s fully compatible with React 18’s concurrent features including:
- Concurrent rendering
- Automatic batching
- Transitions
- Suspense (when combined with proper error boundaries)
Server-Side Rendering (SSR)
TanStack Store works seamlessly with SSR. Create stores outside of components and initialize them with your server-side data:Performance Tips
- Use selectors wisely: Select only what you need to minimize re-renders
- Leverage equality functions: Use
shallowor custom comparisons for complex objects - Memoize selectors: For expensive computations, consider memoizing your selector functions
- Create multiple stores: Instead of one large store, create multiple smaller stores for different domains
Derived Stores
You can create derived stores that automatically update based on other stores:API Reference
For detailed API documentation, see:- useStore - React hook for subscribing to stores
- shallow - Shallow equality comparison utility
- createStore - Core store creation API