Introduction
The Auction Platform uses Zustand for state management. Zustand provides a lightweight, hook-based API for managing global state without the complexity of traditional state management libraries.Why Zustand?
Simple API
Minimal boilerplate with a straightforward, hook-based interface
No Providers
No context providers needed - stores work out of the box
Type-Safe
Full TypeScript support with excellent type inference
Performant
Fine-grained subscriptions prevent unnecessary re-renders
Store Organization
Stores are located insrc/app/store/ and organized by domain:
Auth Store Example
The auth store manages authentication state and user session:Store Structure
Each Zustand store follows this pattern:Using Stores in Components
Subscribe to Entire Store
Subscribe to Specific State (Recommended)
Using selectors ensures components only re-render when the specific state they depend on changes.
Access Store Outside React
Stores can be accessed outside React components:- API client for authentication checks (src/app/api/client.ts:28)
- Route guards in TanStack Router
- Application initialization (src/main.tsx:17)
State Initialization
The auth store is initialized before the application renders:The
init() action fetches the current user session from the server, ensuring auth state is ready before routing begins.Common Patterns
Async Actions
Stores can contain async actions that fetch data and update state:Computed Values
Derive computed values from state:Immer for Complex Updates
For complex nested state updates, use theimmer middleware:
Store Actions vs Services
- Store Actions
- Feature Services
Use for:
- Simple state updates
- State transformations
- Synchronous operations
- Cross-feature state coordination
DevTools Integration
Zustand integrates with Redux DevTools for debugging:Best Practices
Use Selectors
Use Selectors
Always use selectors to subscribe to specific state slices and prevent unnecessary re-renders.
Keep Stores Focused
Keep Stores Focused
Create separate stores for different domains (auth, cart, settings) rather than one large store.
Colocate Actions
Colocate Actions
Define actions in the same store file to keep related logic together.
Type Everything
Type Everything
Use TypeScript for full type safety on state and actions.
Async in Actions
Async in Actions
Handle async operations in store actions, but consider moving complex logic to services.
Performance Optimization
Shallow Equality
For selecting multiple values, use shallow equality:Transient Updates
For high-frequency updates that don’t need to trigger re-renders:Related Resources
Architecture Overview
Learn about the overall architecture
API Client
Understand how stores interact with the API
Routing
See how stores are used in route guards
Zustand Docs
Official Zustand documentation