Overview
createReactStoreContext creates a Zustand store with React context integration, allowing you to have multiple isolated store instances within the same React tree. This is useful when you need different parts of your application to have their own store instances.
Import
Signature
Parameters
Configuration options for the context (inherits from
createCustomContext)Display name for the context
Name of the hook for error messages
Name of the provider for error messages
Custom error message when hook is used outside of provider
Return Value
Hook to access the store from context
- Without selector: Returns the entire state
- With selector: Returns selected value from state
Types
Examples
Basic Form Store with Context
Multiple Store Instances
Wizard/Multi-Step Form
Modal/Dialog Store
When to Use
UsecreateReactStoreContext when you need:
- Multiple independent instances: Different parts of your app need their own store instances
- Scoped state: State should be scoped to a specific component tree
- Dynamic stores: Stores need to be created with different initial values
- Component isolation: Components should work independently with their own state
createReactStore when you need:
- Global state: Single source of truth across your entire app
- Singleton store: One store instance for the entire application
- Simple state management: No need for multiple instances
Best Practices
- Create store in useMemo: Always wrap store creation in
useMemoto avoid creating new instances on re-renders - Type your state: Use TypeScript for better developer experience
- Use selectors: Always use selectors to avoid unnecessary re-renders
- Provide meaningful names: Set context name, hook name, and provider name for better error messages
- Clean up: Stores are automatically cleaned up when the provider unmounts