Shared UI state
A React component needs shared client state without wiring a context provider.
Zustand · Pipe
Zustand's create builds a hook-based store containing state and actions. Components select the data they need, and set applies merged updates without requiring a provider.
A Zustand store is created with create, which returns a hook containing state and actions. Components call that hook with selectors to subscribe to only the state they need; updates use set, whose partial results are merged into the store.
create((set) => ({ state, actions }))| Name | Type | Description |
|---|---|---|
stateCreator | (set) => state and actions | State creator function receiving set and returning the store's initial state and actions. |
A hook for accessing the store state and actions, with selector-based subscriptions.
create is directly usable as a React hook for reading store state.set with a partial object merges those fields into the existing state.set for updates rather than replacing state unintentionally; partial updates are merged.import { create } from 'zustand'
type Store = {
count: number
increment: () => void
}
const useStore = create<Store>((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}))
export function Counter() {
const count = useStore((state) => state.count)
const increment = useStore((state) => state.increment)
return <button onClick={increment}>{count}</button>
}Creates a typed Zustand hook containing state and an action, then selects each value independently in a React component.
A React component needs shared client state without wiring a context provider.
Several components need to read and update the same application values.
A component should update only when one selected store value changes.
create function produce?create receives a state creator and returns a hook. The state creator defines initial values and actions, while actions call set to update the store.
Follow-up: How can a component avoid subscribing to unrelated changes? Use a selector such as (state) => state.count, so it subscribes to the selected value.
A selector reads the required part of the store from the hook. The consuming component re-renders when that selected state changes.
Follow-up: Can actions be selected separately? Yes; select the action function independently, just as you select a state value.
Zustand updates are performed through set. The updater can derive a new partial object from the current state, and Zustand merges that partial update.
Follow-up: What is a practical store design pattern for larger applications? Keep related state and actions together, and split a large store into slices when needed.
createsetselectoruseBearslices