Sub topic 15
Vanilla stores and per-tree stores with context
This chapter assumes you can write a Zustand store with create, read it with selectors, and use React context and useRef. It covers the case where one module-level store is the wrong choice.
Why a module-level store can be a problem
A store made with create lives at module level, so the whole app shares one instance. That is usually what you want. It causes trouble in three cases:
- Server rendering, where one module-level store is shared between requests and can leak one user's data to another.
- A component that appears several times on a page, where each copy needs its own state.
- Tests or tools that need a fresh store with its own initial values.
The fix is a store that is not tied to a hook. Each provider creates its own instance.
Vanilla stores with createStore
createStore comes from zustand and returns a store object. It has getState, setState and subscribe, but it is not a React hook. Pass it to useStore to read it in a component.
A per-tree store with context
This example builds a store per provider and exposes it through a custom hook.
import { createContext, useContext, useRef, type ReactNode } from 'react'
import { createStore, useStore } from 'zustand'
interface CounterState {
count: number
increment: () => void
}
const createCounterStore = (initialCount: number) =>
createStore<CounterState>()((set) => ({
count: initialCount,
increment: () => set((state) => ({ count: state.count + 1 })),
}))
type CounterStore = ReturnType<typeof createCounterStore>
const CounterContext = createContext<CounterStore | null>(null)
export function CounterProvider({ initialCount, children }: { initialCount: number; children: ReactNode }) {
const storeRef = useRef<CounterStore | null>(null)
if (storeRef.current === null) {
storeRef.current = createCounterStore(initialCount)
}
return <CounterContext.Provider value={storeRef.current}>{children}</CounterContext.Provider>
}
export function useCounter<T>(selector: (state: CounterState) => T): T {
const store = useContext(CounterContext)
if (!store) throw new Error('useCounter must be used inside CounterProvider')
return useStore(store, selector)
}Four parts do the work:
createCounterStoreis a factory. Each call returns a new, independent store seeded withinitialCount.useRefholds the instance. Thenullcheck creates the store on the first render only, so re-renders do not replace it and wipe the state.- The context carries the store object, not the state. Because the object never changes, components that read context do not re-render when the state changes.
useCounterpasses the store and a selector touseStore. Selectors behave as they do withcreate, so components re-render only when the selected value changes.
Two providers with different initialCount values now hold separate counts, even on the same page.
Common errors
- Calling the factory in the render body. Writing
value={createCounterStore(initialCount)}makes a new store on every render and resets the state. Keep theuseRefguard. - Using the hook outside the provider. The
useContextcall returnsnull. The explicitthrowgives a clear message instead of a vague error onnull. - Expecting
initialCountchanges to update the store. The store is created once. A later prop change does not reach it. Call an action if the value must follow the prop.
Exercise
A CounterProvider is written as <CounterContext.Provider value={createCounterStore(initialCount)}> with no useRef. What goes wrong, and how do you fix it?
Show answer
Every render of the provider creates a new store, so the state resets whenever the provider re-renders. Create the store once and keep it in a ref (useRef with a null check), then pass storeRef.current as the context value.