Sub topic 15
Vanilla Stores and Per-Tree Stores with Context
What this chapter assumes
You should already know how to build a store with create, read it with selectors, and write actions with set. This chapter covers the store underneath create, which has no React dependency. It also shows how to give each part of your component tree its own store instance.
The store behind create
The hook you get from create is a vanilla store with a React hook attached. The vanilla store holds the state, the set and get functions, and a list of subscribers. It has no React code in it. The hook adds a subscription to that store, so components re-render when their selected value changes.
createStore gives you the store without the hook:
import { createStore } from 'zustand/vanilla'
interface CounterState {
count: number
increment: () => void
}
export const counterStore = createStore<CounterState>()((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}))
counterStore.getState().increment()
console.log(counterStore.getState().count) // 1
const unsubscribe = counterStore.subscribe((state, prevState) => {
console.log('count changed from', prevState.count, 'to', state.count)
})
counterStore.setState({ count: 10 })
unsubscribe()The returned object has four methods: getState, setState, subscribe and getInitialState. A store made with create has the same four methods, because create calls createStore internally. That is why useCounterStore.getState() works in the previous chapter's examples.
Use createStore when the store must work without React. Examples are a utility module, a WebSocket handler, or a library that supports several frameworks.
Reading a vanilla store in React
React components read a vanilla store with the useStore hook. It takes the store and a selector:
import { useStore } from 'zustand'
import { counterStore } from './counterStore'
export function Count() {
const count = useStore(counterStore, (state) => state.count)
return <p>Count: {count}</p>
}Selector rules are unchanged. A selector that returns a new object on every call still causes extra renders, and you still wrap it in useShallow. create is a shortcut for createStore plus a useStore call bound to that store.
Why a module-level store can be wrong
A store created at module level is a singleton. Every component in the application, and every importer of the module, shares one instance. Most apps want this. Three situations break it:
- Server rendering. The module is evaluated once per server process. State set while rendering one user's request is visible to the next request. This is a data leak.
- Repeated widgets. Two instances of the same component, such as two editors or two cart widgets, need separate state. A singleton gives them the same state.
- Per-instance initial values. A page may receive props or server data that must seed the store. A module-level store cannot read props, because it exists before any component renders.
The fix is to create the store inside the tree, one instance per provider, and pass it down with React context.
A per-tree store with context
This pattern has three parts. A factory function builds a new store. A provider creates one instance and puts it in context. A hook reads the store from context and calls useStore.
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)
}Save this as CounterProvider.tsx. The file contains JSX, so it needs the .tsx extension.
Each piece does one job:
createCounterStoretakes the initial value as an argument. This is how props or server data seed the store.ReturnType<typeof createCounterStore>gives the store's type without a hand-written interface.- The context holds the store object. It never holds the state itself.
- The
useRefcheck creates the store once, on the first render. Later renders reusestoreRef.current. useCounterthrows a clear error if a component is rendered outside the provider. Without the check,useStorewould fail with a confusing message aboutundefined.
Now two providers give two independent counters:
import { CounterProvider, useCounter } from './CounterProvider'
function Counter({ label }: { label: string }) {
const count = useCounter((state) => state.count)
const increment = useCounter((state) => state.increment)
return (
<button onClick={increment}>
{label}: {count}
</button>
)
}
export function App() {
return (
<>
<CounterProvider initialCount={0}>
<Counter label="First" />
</CounterProvider>
<CounterProvider initialCount={100}>
<Counter label="Second" />
</CounterProvider>
</>
)
}Clicking "First" changes only the first store. The second starts at 100 and stays independent.
Edge cases and details
The store is created once per provider mount. The ref keeps the same store across re-renders. If the provider unmounts and mounts again, you get a new store with fresh state. If you need state to survive that, combine this pattern with persist, or keep the provider higher in the tree.
Changing initialCount later does nothing. The factory runs only on the first render, so a prop change after that is ignored. This matches how useState treats its initial value. If the store must follow a prop, call an action from an effect, or give the provider a key so React remounts it.
Middleware still works. createStore accepts the same wrappers as create. You can write createStore<CounterState>()(devtools(persist(...))) inside the factory. When you persist a per-tree store, give each instance a distinct storage name, or the instances overwrite each other's saved data.
Why useRef and not a module variable. Calling createCounterStore at module level would bring back the singleton. Calling it directly in the component body would create a new store on every render and lose state. Lazy initialization through the ref avoids both. useState(() => createCounterStore(initialCount)) also works and is a common alternative.
The context value never changes. The provider passes the same store object on every render, so context consumers do not re-render when state changes. Re-renders come only from the useStore subscription and its selector. You keep fine-grained updates and still get per-tree isolation.
Non-React code can reach the store through context. Pass the store object from the provider to anything that needs getState or subscribe, for example from an effect. A global useCounterStore.getState() does not exist in this pattern, because there is no global store.
Choosing between the three forms
| Form | Created with | Instances | Use when |
|---|---|---|---|
| Hook store | `create` | One per module | A client-side app with one shared state |
| Vanilla singleton | `createStore` | One per module | Non-React code or several frameworks share the store |
| Per-tree store | `createStore` plus context | One per provider | SSR, repeated widgets, or per-instance initial values |
Exercise
A page renders two <CounterProvider> components. A developer changes initialCount on the first one from 0 to 5 after the page has loaded. The first counter still shows its old value. Why does this happen, and how can the developer make the store restart with the new value?
Show answer
The factory createCounterStore runs only when storeRef.current is null, which is the first render. Later prop changes are ignored, the same way useState ignores a changed initial value. To restart the store, give the provider a key that includes the value, for example <CounterProvider key={initialCount} initialCount={initialCount}>. React then unmounts the old provider and mounts a new one, which creates a new store with the new initial value.
Exercise
Why does useCounter throw an error when the context value is null, and why is the context value the store object rather than the state?
Show answer
Components rendered outside the provider would otherwise receive null and fail inside useStore with an unclear error. The explicit check gives a message that names the missing provider. The context holds the store object, which never changes identity, so context consumers do not re-render on state changes. Only the selector subscription inside useStore triggers re-renders.