A small, fast and scalable bearbones state-management solution using simplified flux principles. Has a comfy api based on hooks, isn't boilerplatey or opinionated.
Don't disregard it because it's cute. It has quite the claws, lots of time was spent to deal with common pitfalls, like the dreaded zombie child problem, react concurrency, and context loss between mixed renderers. It may be the one state-manager in the React space that gets all of these right.
You can try a live demo here.
npm install zustand
First create a store
Your store is a hook! You can put anything in it: primitives, objects, functions. The set
function merges state.
import create from 'zustand'
const useStore = create(set => ({
bears: 0,
increasePopulation: () => set(state => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 })
}))
Then bind your components, and that's it!
Use the hook anywhere, no providers needed. Select your state and the component will re-render on changes.
function BearCounter() {
const bears = useStore(state => state.bears)
return <h1>{bears} around here ...</h1>
}
function Controls() {
const increasePopulation = useStore(state => state.increasePopulation)
return <button onClick={increasePopulation}>one up</button>
}
Why zustand over redux?
Why zustand over context?
- Less boilerplate
- Renders components only on changes
- Centralized, action-based state management
Recipes
Fetching everything
You can, but bear in mind that it will cause the component to update on every state change!
const state = useStore()
Selecting multiple state slices
It detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.
const nuts = useStore(state => state.nuts)
const honey = useStore(state => state.honey)
If you want to construct a single object with multiple state-picks inside, similar to redux's mapStateToProps, you can tell zustand that you want the object to be diffed shallowly by passing the shallow
equality function.
import shallow from 'zustand/shallow'
const { nuts, honey } = useStore(state => ({ nuts: state.nuts, honey: state.honey }), shallow)
const [nuts, honey] = useStore(state => [state.nuts, state.honey], shallow)
const treats = useStore(state => Object.keys(state.treats), shallow)
For more control over re-rendering, you may provide any custom equality function.
const treats = useStore(
state => state.treats,
(oldTreats, newTreats) => compare(oldTreats, newTreats)
)
Memoizing selectors
It is generally recommended to memoize selectors with useCallback. This will prevent unnecessary computations each render. It also allows React to optimize performance in concurrent mode.
const fruit = useStore(useCallback(state => state.fruits[id], [id]))
If a selector doesn't depend on scope, you can define it outside the render function to obtain a fixed reference without useCallback.
const selector = state => state.berries
function Component() {
const berries = useStore(selector)
Overwriting state
The set
function has a second argument, false
by default. Instead of merging, it will replace the state model. Be careful not to wipe out parts you rely on, like actions.
import omit from "lodash-es/omit"
const useStore = create(set => ({
salmon: 1,
tuna: 2,
deleteEverything: () => set({ }, true),
deleteTuna: () => set(state => omit(state, ['tuna']), true)
}))
Async actions
Just call set
when you're ready, zustand doesn't care if your actions are async or not.
const useStore = create(set => ({
fishies: {},
fetch: async pond => {
const response = await fetch(pond)
set({ fishies: await response.json() })
}
}))
Read from state in actions
set
allows fn-updates set(state => result)
, but you still have access to state outside of it through get
.
const useStore = create((set, get) => ({
sound: "grunt",
action: () => {
const sound = get().sound
}
})
Reading/writing state and reacting to changes outside of components
Sometimes you need to access state in a non-reactive way, or act upon the store. For these cases the resulting hook has utility functions attached to its prototype.
const useStore = create(() => ({ paw: true, snout: true, fur: true }))
const paw = useStore.getState().paw
const unsub1 = useStore.subscribe(console.log)
useStore.setState({ paw: false })
unsub1()
useStore.destroy()
function Component() {
const paw = useStore(state => state.paw)
Using subscribe with selector
If you need to subscribe with selector,
subscribeWithSelector
middleware will help.
With this middleware subscribe
accepts an additional signature:
subscribe(selector, callback, options?: { equalityFn, fireImmediately }): Unsubscribe
import { subscribeWithSelector } from 'zustand/middleware'
const useStore = create(subscribeWithSelector(() => ({ paw: true, snout: true, fur: true })))
const unsub2 = useStore.subscribe(state => state.paw, console.log)
const unsub3 = useStore.subscribe(state => state.paw, (paw, previousPaw) => console.log(paw, previousPaw))
const unsub4 = useStore.subscribe(state => [state.paw, state.fur], console.log, { equalityFn: shallow })
const unsub5 = useStore.subscribe(state => state.paw, console.log, { fireImmediately: true })
How to type store with `subscribeWithSelector` in TypeScript
import create, { GetState, SetState } from 'zustand'
import { StoreApiWithSubscribeWithSelector } from 'zustand/middleware'
type BearState = {
paw: boolean
snout: boolean
fur: boolean
}
const useStore = create<
BearState,
SetState<BearState>,
GetState<BearState>,
StoreApiWithSubscribeWithSelector<BearState>
>(subscribeWithSelector(() => ({ paw: true, snout: true, fur: true })))
For more complex typing with multiple middlewares,
Please refer middlewareTypes.test.tsx.
Using zustand without React
Zustands core can be imported and used without the React dependency. The only difference is that the create function does not return a hook, but the api utilities.
import create from 'zustand/vanilla'
const store = create(() => ({ ... }))
const { getState, setState, subscribe, destroy } = store
You can even consume an existing vanilla store with React:
import create from 'zustand'
import vanillaStore from './vanillaStore'
const useStore = create(vanillaStore)
:warning: Note that middlewares that modify set
or get
are not applied to getState
and setState
.
Transient updates (for often occuring state-changes)
The subscribe function allows components to bind to a state-portion without forcing re-render on changes. Best combine it with useEffect for automatic unsubscribe on unmount. This can make a drastic performance impact when you are allowed to mutate the view directly.
const useStore = create(set => ({ scratches: 0, ... }))
function Component() {
const scratchRef = useRef(useStore.getState().scratches)
useEffect(() => useStore.subscribe(
state => (scratchRef.current = state.scratches)
), [])
Sick of reducers and changing nested state? Use Immer!
Reducing nested structures is tiresome. Have you tried immer?
import produce from 'immer'
const useStore = create(set => ({
lush: { forest: { contains: { a: "bear" } } },
clearForest: () => set(produce(state => {
state.lush.forest.contains = null
}))
}))
const clearForest = useStore(state => state.clearForest)
clearForest();
Middleware
You can functionally compose your store any way you like.
const log = config => (set, get, api) => config(args => {
console.log(" applying", args)
set(args)
console.log(" new state", get())
}, get, api)
const immer = config => (set, get, api) => config((partial, replace) => {
const nextState = typeof partial === 'function'
? produce(partial)
: partial
return set(nextState, replace)
}, get, api)
const useStore = create(
log(
immer((set) => ({
bees: false,
setBees: (input) => set((state) => void (state.bees = input)),
})),
),
)
How to pipe middlewares
import create from "zustand"
import produce from "immer"
import pipe from "ramda/es/pipe"
const createStore = pipe(log, immer, create)
const useStore = createStore(set => ({
bears: 1,
increasePopulation: () => set(state => ({ bears: state.bears + 1 }))
}))
export default useStore
For a TS example see the following discussion
How to type immer middleware in TypeScript
There is a reference implementation in middlewareTypes.test.tsx with some use cases.
You can use any simplified variant based on your requirement.
Persist middleware
You can persist your store's data using any kind of storage.
import create from "zustand"
import { persist } from "zustand/middleware"
export const useStore = create(persist(
(set, get) => ({
fishes: 0,
addAFish: () => set({ fishes: get().fishes + 1 })
}),
{
name: "food-storage",
getStorage: () => sessionStorage,
}
))
See the full documentation for this middleware.
Can't live without redux-like reducers and action types?
const types = { increase: "INCREASE", decrease: "DECREASE" }
const reducer = (state, { type, by = 1 }) => {
switch (type) {
case types.increase: return { grumpiness: state.grumpiness + by }
case types.decrease: return { grumpiness: state.grumpiness - by }
}
}
const useStore = create(set => ({
grumpiness: 0,
dispatch: args => set(state => reducer(state, args)),
}))
const dispatch = useStore(state => state.dispatch)
dispatch({ type: types.increase, by: 2 })
Or, just use our redux-middleware. It wires up your main-reducer, sets initial state, and adds a dispatch function to the state itself and the vanilla api. Try this example.
import { redux } from 'zustand/middleware'
const useStore = create(redux(reducer, initialState))
Calling actions outside a React event handler
Because React handles setState
synchronously if it's called outside an event handler. Updating the state outside an event handler will force react to update the components synchronously, therefore adding the risk of encountering the zombie-child effect.
In order to fix this, the action needs to be wrapped in unstable_batchedUpdates
import { unstable_batchedUpdates } from 'react-dom'
const useStore = create((set) => ({
fishes: 0,
increaseFishes: () => set((prev) => ({ fishes: prev.fishes + 1 }))
}))
const nonReactCallback = () => {
unstable_batchedUpdates(() => {
useStore.getState().increaseFishes()
})
}
More details: https://github.com/pmndrs/zustand/issues/302
Redux devtools
import { devtools } from 'zustand/middleware'
const useStore = create(devtools(store))
const useStore = create(devtools(redux(reducer, initialState)))
devtools takes the store function as its first argument, optionally you can name the store or configure serialize options with a second argument.
Name store: devtools(store, {name: "MyStore"})
, which will be prefixed to your actions.
Serialize options: devtools(store, { serialize: { options: true } })
.
devtools will only log actions from each separated store unlike in a typical combined reducers redux store. See an approach to combining stores https://github.com/pmndrs/zustand/issues/163
React context
The store created with create
doesn't require context providers. In some cases, you may want to use contexts for dependency injection or if you want to initialize your store with props from a component. Because the store is a hook, passing it as a normal context value may violate rules of hooks. To avoid misusage, a special createContext
is provided.
import create from 'zustand'
import createContext from 'zustand/context'
const { Provider, useStore } = createContext()
const createStore = () => create(...)
const App = () => (
<Provider createStore={createStore}>
...
</Provider>
)
const Component = () => {
const state = useStore()
const slice = useStore(selector)
...
}
createContext usage in real components
import create from "zustand";
import createContext from "zustand/context";
const { Provider, useStore } = createContext();
const createStore = () =>
create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 })
}));
const Button = () => {
return (
{}
<Provider createStore={createStore}>
<ButtonChild />
</Provider>
);
};
const ButtonChild = () => {
const state = useStore();
return (
<div>
{state.bears}
<button
onClick={() => {
state.increasePopulation();
}}
>
+
</button>
</div>
);
};
export default function App() {
return (
<div className="App">
<Button />
<Button />
</div>
);
}
createContext usage with initialization from props (in TypeScript)
import create from "zustand";
import createContext from "zustand/context";
type BearState = {
bears: number
increase: () => void
}
const { Provider, useStore } = createContext<BearState>();
export default function App({ initialBears }: { initialBears: number }) {
return (
<Provider
createStore={() =>
create((set) => ({
bears: initialBears,
increase: () => set((state) => ({ bears: state.bears + 1 })),
}))
}
>
<Button />
</Provider>
)
}
Typing your store and combine
middleware
type BearState = {
bears: number
increase: (by: number) => void
}
interface BearState {
bears: number
increase: (by: number) => void
}
const useStore = create<BearState>(set => ({
bears: 0,
increase: (by) => set(state => ({ bears: state.bears + by })),
}))
Or, use combine
and let tsc infer types. This merges two states shallowly.
import { combine } from 'zustand/middleware'
const useStore = create(
combine(
{ bears: 0 },
(set) => ({ increase: (by: number) => set((state) => ({ bears: state.bears + by })) })
),
)
Typing with multiple middleware might require some TypeScript knowledge. Refer some working examples in middlewareTypes.test.tsx.
Best practices
Testing
For information regarding testing with Zustand, visit the dedicated Wiki page.
3rd-Party Libraries
Some users may want to extends Zustand's feature set which can be done using 3rd-party libraries made by the community. For information regarding 3rd-party libraries with Zustand, visit the dedicated Wiki page.
Comparison with other libraries