Sub topic 2
Your first store with create
A Zustand store is a small object that holds shared state and the functions that change it. This chapter builds one with create, explains what create returns, and covers how set updates state. It also lists the mistakes people make with their first store.
Prerequisites
This chapter assumes you know:
- React function components and the
useStatehook. - JavaScript modules, arrow functions and object spread.
- Why shared state and prop drilling are a problem.
- Why state updates should be immutable, meaning you build a new object instead of editing the old one.
The examples use TypeScript. If you use plain JavaScript, drop the interface and the type argument.
What create does
create is the function you import from the zustand package. You give it a function, called the state creator, that describes your initial state and your actions. It returns a React hook. Calling that hook inside a component reads from the store.
Three facts explain most of Zustand's behavior:
- The store lives outside React, at module level. It is not a component and has no provider.
- The state creator receives
set, the function that updates the state. It also receivesgetand anapiobject, which later chapters use. - Every component that calls the hook subscribes to the store. When the state changes, React re-renders the subscribed components.
Writing the store
Here is a counter store. State and actions sit together in one object.
import { create } from 'zustand'
interface CounterState {
count: number
increment: () => void
reset: () => void
}
export const useCounterStore = create<CounterState>()((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
reset: () => set({ count: 0 }),
}))Read it from the inside out:
- The object returned by the arrow function is the initial state.
countis data.incrementandresetare actions, which are ordinary functions stored in the state. settakes either a partial state object or a function. The function receives the current state and returns a partial state object.- The result is merged into the existing state.
resetpasses onlycount, and the actions stay in place. - The hook is named
useCounterStore. Theuseprefix is a convention, and it lets the React lint rules treat the value as a hook.
The odd-looking create<CounterState>()(...) has two sets of parentheses on purpose. The first call fixes the state type. The second receives the state creator. Splitting them lets TypeScript infer the types of middleware you add later. A later chapter covers typing in more detail. For now, always write create<T>()(...) and don't shorten it to create<T>(...).
Using the store in components
Components call the hook with a selector. A selector is a function that takes the whole state and returns the part the component needs.
import { useCounterStore } from './counterStore'
function Count() {
const count = useCounterStore((state) => state.count)
return <p>Count: {count}</p>
}
function Controls() {
const increment = useCounterStore((state) => state.increment)
return <button onClick={increment}>Add one</button>
}There is no provider to add. Count and Controls can sit anywhere in the tree, and both reach the same store. After a click, Count re-renders because its selected value changed. Controls does not re-render, because the increment function is the same reference as before. The next chapter covers selectors in depth.
How set merges state
set does a shallow merge. It copies the top-level keys of the object you pass over the existing state. It does not merge nested objects.
import { create } from 'zustand'
interface ProfileState {
user: { name: string; age: number }
rename: (name: string) => void
}
export const useProfileStore = create<ProfileState>()((set) => ({
user: { name: 'Ada', age: 36 },
// Wrong: replaces the whole user object, so age is lost at runtime.
// (TypeScript reports an error here because age is missing.)
// rename: (name) => set({ user: { name } }),
rename: (name) => set((state) => ({ user: { ...state.user, name } })),
}))To change one nested field, spread the old nested object into a new one, as rename does above. Deeply nested state gets tedious this way. The immer middleware, covered in a later chapter, is the usual fix.
set also takes a second argument, replace. When it is true, the state is replaced and not merged:
useCounterStore.setState({ count: 10 }, true)This removes every key you left out, including your actions. increment would no longer exist after that call. Use replace only when you pass a complete state object. Restoring a saved snapshot between tests is the typical case.
Functional and object updates
Choose the form of set by whether the new value depends on the old one.
| Situation | Form | Example |
|---|---|---|
| New value does not depend on current state | Object | `set({ count: 0 })` |
| New value is computed from current state | Function | `set((state) => ({ count: state.count + 1 }))` |
The function form always receives the latest state when it runs. An object built from a value you read earlier may be stale if other updates happened in between. Prefer the function form for counters, toggles and list changes.
You can also read state inside an action with get, the second argument of the state creator. This is useful when an action needs the current state but doesn't update it:
import { create } from 'zustand'
interface CartState {
items: string[]
addItem: (item: string) => void
logCount: () => void
}
export const useCartStore = create<CartState>()((set, get) => ({
items: [],
addItem: (item) => set((state) => ({ items: [...state.items, item] })),
logCount: () => console.log(`Cart has ${get().items.length} items`),
}))Common errors
These are the errors you are most likely to hit with a first store.
- Mutating state. Writing
state.items.push(item)changes the array in place. The array reference stays the same, so subscribers see no change and components don't update. Always build a new array or object, asaddItemdoes with the spread. - Forgetting the second pair of parentheses.
create<CounterState>((set) => ...)can work at runtime, but it breaks type inference once you add middleware. Usecreate<CounterState>()(...). - Selecting the whole store. Calling
useCounterStore()with no selector subscribes the component to every change. It works, but it re-renders more than necessary. Pass a selector. - Replacing by accident. Passing
trueas the second argument tosetdeletes your actions unless the object you pass includes them. - Creating the store inside a component. If
createruns in a component body, each render makes a new store and state is lost. Callcreateonce, at module level.
Exercise
Exercise
You write a store with user: { name: 'Ada', age: 36 } and an action birthday: () => set((state) => ({ user: { age: state.user.age + 1 } })). After the action runs, what is wrong with the state, and how do you fix the action?
Show answer
set merges only at the top level, so the user key is replaced by { age: 37 } and name is lost. TypeScript also reports an error because name is missing. Spread the old object into the new one: set((state) => ({ user: { ...state.user, age: state.user.age + 1 } })).
Exercise
Why does Controls in the earlier example not re-render when count changes, even though it uses the same store as Count?
Show answer
Controls selects only state.increment. The action is defined once and keeps the same reference when count changes, so the selected value is unchanged and the component is not re-rendered.