Learn how to initialize Zustand stores with props using dependency injection and React Context
In cases where dependency injection is needed, such as when a store should be initialized with props from a component, the recommended approach is to use a vanilla store with React.context.
1
Create a store with createStore
First, create a store creator function that accepts initial props:
Create a custom hook to mimic the hook returned by create:
import { useContext } from 'react'import { useStore } from 'zustand'function useBearContext<T>(selector: (state: BearState) => T): T { const store = useContext(BearContext) if (!store) throw new Error('Missing BearContext.Provider in the tree') return useStore(store, selector)}
This pattern is particularly useful when you need different instances of the same store in different parts of your application tree, each initialized with different props.