Zustand

Bear necessities for state management in React

README

Build Status Build Size Version Downloads Discord Shield

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.

  1. ```bash
  2. npm install zustand # or yarn add zustand
  3. ```

:warning: This readme is written for JavaScript users. If you are a TypeScript user, don't miss TypeScript Usage.

First create a store


Your store is a hook! You can put anything in it: primitives, objects, functions. State has to be updated immutably and the set function merges state to help it.

  1. ```jsx
  2. import create from 'zustand'

  3. const useBearStore = create((set) => ({
  4.   bears: 0,
  5.   increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  6.   removeAllBears: () => set({ bears: 0 }),
  7. }))
  8. ```

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.

  1. ```jsx
  2. function BearCounter() {
  3.   const bears = useBearStore((state) => state.bears)
  4.   return <h1>{bears} around here ...</h1>
  5. }

  6. function Controls() {
  7.   const increasePopulation = useBearStore((state) => state.increasePopulation)
  8.   return <button onClick={increasePopulation}>one up</button>
  9. }
  10. ```

Why zustand over redux?


- Simple and un-opinionated
- Makes hooks the primary means of consuming state
- Doesn't wrap your app in context providers

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!

  1. ```jsx
  2. const state = useBearStore()
  3. ```

Selecting multiple state slices


It detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.

  1. ```jsx
  2. const nuts = useBearStore((state) => state.nuts)
  3. const honey = useBearStore((state) => state.honey)
  4. ```

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.

  1. ```jsx
  2. import shallow from 'zustand/shallow'

  3. // Object pick, re-renders the component when either state.nuts or state.honey change
  4. const { nuts, honey } = useBearStore(
  5.   (state) => ({ nuts: state.nuts, honey: state.honey }),
  6.   shallow
  7. )

  8. // Array pick, re-renders the component when either state.nuts or state.honey change
  9. const [nuts, honey] = useBearStore(
  10.   (state) => [state.nuts, state.honey],
  11.   shallow
  12. )

  13. // Mapped picks, re-renders the component when state.treats changes in order, count or keys
  14. const treats = useBearStore((state) => Object.keys(state.treats), shallow)
  15. ```

For more control over re-rendering, you may provide any custom equality function.

  1. ```jsx
  2. const treats = useBearStore(
  3.   (state) => state.treats,
  4.   (oldTreats, newTreats) => compare(oldTreats, newTreats)
  5. )
  6. ```

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.

  1. ```jsx
  2. import omit from 'lodash-es/omit'

  3. const useFishStore = create((set) => ({
  4.   salmon: 1,
  5.   tuna: 2,
  6.   deleteEverything: () => set({}, true), // clears the entire store, actions included
  7.   deleteTuna: () => set((state) => omit(state, ['tuna']), true),
  8. }))
  9. ```

Async actions


Just call set when you're ready, zustand doesn't care if your actions are async or not.

  1. ```jsx
  2. const useFishStore = create((set) => ({
  3.   fishies: {},
  4.   fetch: async (pond) => {
  5.     const response = await fetch(pond)
  6.     set({ fishies: await response.json() })
  7.   },
  8. }))
  9. ```

Read from state in actions


set allows fn-updates set(state => result), but you still have access to state outside of it through get.

  1. ```jsx
  2. const useSoundStore = create((set, get) => ({
  3.   sound: "grunt",
  4.   action: () => {
  5.     const sound = get().sound
  6.     // ...
  7.   }
  8. })
  9. ```

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.

  1. ```jsx
  2. const useDogStore = create(() => ({ paw: true, snout: true, fur: true }))

  3. // Getting non-reactive fresh state
  4. const paw = useDogStore.getState().paw
  5. // Listening to all changes, fires synchronously on every change
  6. const unsub1 = useDogStore.subscribe(console.log)
  7. // Updating state, will trigger listeners
  8. useDogStore.setState({ paw: false })
  9. // Unsubscribe listeners
  10. unsub1()
  11. // Destroying the store (removing all listeners)
  12. useDogStore.destroy()

  13. // You can of course use the hook as you always would
  14. const Component = () => {
  15.   const paw = useDogStore((state) => state.paw)
  16.   ...
  17. ```

Using subscribe with selector


If you need to subscribe with selector,
subscribeWithSelector middleware will help.

With this middleware subscribe accepts an additional signature:

  1. ```ts
  2. subscribe(selector, callback, options?: { equalityFn, fireImmediately }): Unsubscribe
  3. ```

  1. ```js
  2. import { subscribeWithSelector } from 'zustand/middleware'
  3. const useDogStore = create(
  4.   subscribeWithSelector(() => ({ paw: true, snout: true, fur: true }))
  5. )

  6. // Listening to selected changes, in this case when "paw" changes
  7. const unsub2 = useDogStore.subscribe((state) => state.paw, console.log)
  8. // Subscribe also exposes the previous value
  9. const unsub3 = useDogStore.subscribe(
  10.   (state) => state.paw,
  11.   (paw, previousPaw) => console.log(paw, previousPaw)
  12. )
  13. // Subscribe also supports an optional equality function
  14. const unsub4 = useDogStore.subscribe(
  15.   (state) => [state.paw, state.fur],
  16.   console.log,
  17.   { equalityFn: shallow }
  18. )
  19. // Subscribe and fire immediately
  20. const unsub5 = useDogStore.subscribe((state) => state.paw, console.log, {
  21.   fireImmediately: true,
  22. })
  23. ```

Using zustand without React


Zustand 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.

  1. ```jsx
  2. import create from 'zustand/vanilla'

  3. const store = create(() => ({ ... }))
  4. const { getState, setState, subscribe, destroy } = store
  5. ```

You can even consume an existing vanilla store with React:

  1. ```jsx
  2. import create from 'zustand'
  3. import vanillaStore from './vanillaStore'

  4. const useBoundStore = create(vanillaStore)
  5. ```

:warning: Note that middlewares that modify set or get are not applied to getState and setState.

Transient updates (for often occurring 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.

  1. ```jsx
  2. const useScratchStore = create(set => ({ scratches: 0, ... }))

  3. const Component = () => {
  4.   // Fetch initial state
  5.   const scratchRef = useRef(useScratchStore.getState().scratches)
  6.   // Connect to the store on mount, disconnect on unmount, catch state-changes in a reference
  7.   useEffect(() => useScratchStore.subscribe(
  8.     state => (scratchRef.current = state.scratches)
  9.   ), [])
  10.   ...
  11. ```

Sick of reducers and changing nested state? Use Immer!


Reducing nested structures is tiresome. Have you tried immer?

  1. ```jsx
  2. import produce from 'immer'

  3. const useLushStore = create((set) => ({
  4.   lush: { forest: { contains: { a: 'bear' } } },
  5.   clearForest: () =>
  6.     set(
  7.       produce((state) => {
  8.         state.lush.forest.contains = null
  9.       })
  10.     ),
  11. }))

  12. const clearForest = useLushStore((state) => state.clearForest)
  13. clearForest()
  14. ```


Middleware


You can functionally compose your store any way you like.

  1. ```jsx
  2. // Log every time state is changed
  3. const log = (config) => (set, get, api) =>
  4.   config(
  5.     (...args) => {
  6.       console.log('  applying', args)
  7.       set(...args)
  8.       console.log('  new state', get())
  9.     },
  10.     get,
  11.     api
  12.   )

  13. const useBeeStore = create(
  14.   log((set) => ({
  15.     bees: false,
  16.     setBees: (input) => set({ bees: input }),
  17.   }))
  18. )
  19. ```

Persist middleware


You can persist your store's data using any kind of storage.

  1. ```jsx
  2. import create from 'zustand'
  3. import { persist } from 'zustand/middleware'

  4. const useFishStore = create(
  5.   persist(
  6.     (set, get) => ({
  7.       fishes: 0,
  8.       addAFish: () => set({ fishes: get().fishes + 1 }),
  9.     }),
  10.     {
  11.       name: 'food-storage', // unique name
  12.       getStorage: () => sessionStorage, // (optional) by default, 'localStorage' is used
  13.     }
  14.   )
  15. )
  16. ```


Immer middleware


Immer is available as middleware too.

  1. ```jsx
  2. import create from 'zustand'
  3. import { immer } from 'zustand/middleware/immer'

  4. const useBeeStore = create(
  5.   immer((set) => ({
  6.     bees: 0,
  7.     addBees: (by) =>
  8.       set((state) => {
  9.         state.bees += by
  10.       }),
  11.   }))
  12. )
  13. ```

Can't live without redux-like reducers and action types?


  1. ```jsx
  2. const types = { increase: 'INCREASE', decrease: 'DECREASE' }

  3. const reducer = (state, { type, by = 1 }) => {
  4.   switch (type) {
  5.     case types.increase:
  6.       return { grumpiness: state.grumpiness + by }
  7.     case types.decrease:
  8.       return { grumpiness: state.grumpiness - by }
  9.   }
  10. }

  11. const useGrumpyStore = create((set) => ({
  12.   grumpiness: 0,
  13.   dispatch: (args) => set((state) => reducer(state, args)),
  14. }))

  15. const dispatch = useGrumpyStore((state) => state.dispatch)
  16. dispatch({ type: types.increase, by: 2 })
  17. ```

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.

  1. ```jsx
  2. import { redux } from 'zustand/middleware'

  3. const useGrumpyStore = create(redux(reducer, initialState))
  4. ```

Redux devtools


  1. ```jsx
  2. import { devtools } from 'zustand/middleware'

  3. // Usage with a plain action store, it will log actions as "setState"
  4. const usePlainStore = create(devtools(store))
  5. // Usage with a redux store, it will log full action types
  6. const useReduxStore = create(devtools(redux(reducer, initialState)))
  7. ```

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 create a separate instance named "MyStore" in the devtools.

Serialize options: devtools(store, { serialize: { options: true } }).

Logging Actions


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

You can log a specific action type for each set function by passing a third parameter:

  1. ```jsx
  2. const createBearSlice = (set, get) => ({
  3.   eatFish: () =>
  4.     set(
  5.       (prev) => ({ fishes: prev.fishes > 1 ? prev.fishes - 1 : 0 }),
  6.       false,
  7.       'bear/eatFish'
  8.     ),
  9. })
  10. ```

You can also log action's type along with its payload:

  1. ```jsx
  2. const createBearSlice = (set, get) => ({
  3.   addFishes: (count) =>
  4.     set((prev) => ({ fishes: prev.fishes + count }), false, {
  5.       type: 'bear/addFishes',
  6.       count,
  7.     }),
  8. })
  9. ```

If an action type is not provided, it is defaulted to "anonymous". You can customize this default value by providing an anonymousActionType parameter:

  1. ```jsx
  2. devtools(..., { anonymousActionType: 'unknown', ... })
  3. ```

If you wish to disable devtools (on production for instance). You can customize this setting by providing the enabled parameter:

  1. ```jsx
  2. devtools(..., { enabled: false, ... })
  3. ```

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 normal store is a hook, passing it as a normal context value may violate rules of hooks.

The recommended method available since v4 is to use vanilla store.

  1. ```jsx
  2. import { createContext, useContext } from 'react'
  3. import { createStore, useStore } from 'zustand'

  4. const store = createStore(...) // vanilla store without hooks

  5. const StoreContext = createContext()

  6. const App = () => (
  7.   <StoreContext.Provider value={store}>
  8.     ...
  9.   </StoreContext.Provider>
  10. )

  11. const Component = () => {
  12.   const store = useContext(StoreContext)
  13.   const slice = useStore(store, selector)
  14.   ...
  15. ```


TypeScript Usage


Basic typescript usage doesn't require anything special except for writing `create()(...)` instead of `create(...)`...

  1. ```ts
  2. import create from 'zustand'
  3. import { devtools, persist } from 'zustand/middleware'

  4. interface BearState {
  5.   bears: number
  6.   increase: (by: number) => void
  7. }

  8. const useBearStore = create<BearState>()(
  9.   devtools(
  10.     persist(
  11.       (set) => ({
  12.         bears: 0,
  13.         increase: (by) => set((state) => ({ bears: state.bears + by })),
  14.       }),
  15.       {
  16.         name: 'bear-storage',
  17.       }
  18.     )
  19.   )
  20. )
  21. ```

A more complete TypeScript guide is here.

Best practices


- You may wonder how to organize your code for better maintenance: Splitting the store into separate slices.
- Recommended usage for this unopinionated library: Flux inspired practice.

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 doc.

Comparison with other libraries