zustand Documentation

Bear necessities for state management in React

58,556 stars TypeScript TypeScript 1 file ยท ~8,773 tokens #hacktoberfest#hooks#react#react-context#reactjs#redux#state-management
RAW Doc

1. Project Overview & Quickstart (pmndrs/zustand)





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 dealing 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 and read the docs.

bash
npm install zustand

:warning: This readme is written for JavaScript users. If you are a TypeScript user, be sure to check out our TypeScript Usage section.

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.

jsx
import { create } from 'zustand'

const useBearStore = 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 are needed. Select your state and the component will re-render on changes.

jsx
function BearCounter() {
  const bears = useBearStore((state) => state.bears)
  return <h1>{bears} around here ...</h1>
}

function Controls() {
  const increasePopulation = useBearStore((state) => state.increasePopulation)
  return one up
}

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!

jsx
const state = useBearStore()

Selecting multiple state slices

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

jsx
const nuts = useBearStore((state) => state.nuts)
const honey = useBearStore((state) => state.honey)

If you want to construct a single object with multiple state-picks inside, similar to redux's mapStateToProps, you can use useShallow to prevent unnecessary rerenders when the selector output does not change according to shallow equal.

jsx
import { create } from 'zustand'
import { useShallow } from 'zustand/react/shallow'

const useBearStore = create((set) => ({
  nuts: 0,
  honey: 0,
  treats: {},
  // ...
}))

// Object pick, re-renders the component when either state.nuts or state.honey change
const { nuts, honey } = useBearStore(
  useShallow((state) => ({ nuts: state.nuts, honey: state.honey })),
)

// Array pick, re-renders the component when either state.nuts or state.honey change
const [nuts, honey] = useBearStore(
  useShallow((state) => [state.nuts, state.honey]),
)

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

For more control over re-rendering, you may provide any custom equality function (this example requires the use of createWithEqualityFn).

jsx
const treats = useBearStore(
  (state) => state.treats,
  (oldTreats, newTreats) => compare(oldTreats, newTreats),
)

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.

jsx
const useFishStore = create((set) => ({
  salmon: 1,
  tuna: 2,
  deleteEverything: () => set({}, true), // clears the entire store, actions included
  deleteTuna: () => set(({ tuna, ...rest }) => rest, true),
}))

Async actions

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

jsx
const useFishStore = 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.

jsx
const useSoundStore = 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.

:warning: This technique is not recommended for adding state in React Server Components (typically in Next.js 13 and above). It can lead to unexpected bugs and privacy issues for your users. For more details, see #2200.

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

// Getting non-reactive fresh state
const paw = useDogStore.getState().paw
// Listening to all changes, fires synchronously on every change
const unsub1 = useDogStore.subscribe(console.log)
// Updating state, will trigger listeners
useDogStore.setState({ paw: false })
// Unsubscribe listeners
unsub1()

// You can of course use the hook as you always would
function Component() {
  const paw = useDogStore((state) => state.paw)
  ...

Using subscribe with selector

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

With this middleware subscribe accepts an additional signature:

ts
subscribe(selector, callback, options?: { equalityFn, fireImmediately }): Unsubscribe
js
import { subscribeWithSelector } from 'zustand/middleware'
const useDogStore = create(
  subscribeWithSelector(() => ({ paw: true, snout: true, fur: true })),
)

// Listening to selected changes, in this case when "paw" changes
const unsub2 = useDogStore.subscribe((state) => state.paw, console.log)
// Subscribe also exposes the previous value
const unsub3 = useDogStore.subscribe(
  (state) => state.paw,
  (paw, previousPaw) => console.log(paw, previousPaw),
)
// Subscribe also supports an optional equality function
const unsub4 = useDogStore.subscribe(
  (state) => [state.paw, state.fur],
  console.log,
  { equalityFn: shallow },
)
// Subscribe and fire immediately
const unsub5 = useDogStore.subscribe((state) => state.paw, console.log, {
  fireImmediately: true,
})

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.

jsx
import { createStore } from 'zustand/vanilla'

const store = createStore((set) => ...)
const { getState, setState, subscribe, getInitialState } = store

export default store

You can use a vanilla store with useStore hook available since v4.

jsx
import { useStore } from 'zustand'
import { vanillaStore } from './vanillaStore'

const useBoundStore = (selector) => useStore(vanillaStore, selector)

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

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

const Component = () => {
  // Fetch initial state
  const scratchRef = useRef(useScratchStore.getState().scratches)
  // Connect to the store on mount, disconnect on unmount, catch state-changes in a reference
  useEffect(() => useScratchStore.subscribe(
    state => (scratchRef.current = state.scratches)
  ), [])
  ...

Sick of reducers and changing nested states? Use Immer!

Reducing nested structures is tiresome. Have you tried immer?

jsx
import { produce } from 'immer'

const useLushStore = create((set) => ({
  lush: { forest: { contains: { a: 'bear' } } },
  clearForest: () =>
    set(
      produce((state) => {
        state.lush.forest.contains = null
      }),
    ),
}))

const clearForest = useLushStore((state) => state.clearForest)
clearForest()

Alternatively, there are some other solutions.

Persist middleware

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

jsx
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'

const useFishStore = create(
  persist(
    (set, get) => ({
      fishes: 0,
      addAFish: () => set({ fishes: get().fishes + 1 }),
    }),
    {
      name: 'food-storage', // name of the item in the storage (must be unique)
      storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used
    },
  ),
)

See the full documentation for this middleware.

Immer middleware

Immer is available as middleware too.

jsx
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'

const useBeeStore = create(
  immer((set) => ({
    bees: 0,
    addBees: (by) =>
      set((state) => {
        state.bees += by
      }),
  })),
)

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

jsx
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 useGrumpyStore = create((set) => ({
  grumpiness: 0,
  dispatch: (args) => set((state) => reducer(state, args)),
}))

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

Or, just use our redux-middleware. It wires up your main-reducer, sets the initial state, and adds a dispatch function to the state itself and the vanilla API.

jsx
import { redux } from 'zustand/middleware'

const useGrumpyStore = create(redux(reducer, initialState))

Redux devtools

Install the Redux DevTools Chrome extension to use the devtools middleware.

jsx
import { devtools } from 'zustand/middleware'

// Usage with a plain action store, it will log actions as "setState"
const usePlainStore = create(devtools((set) => ...))
// Usage with a redux store, it will log full action types
const useReduxStore = create(devtools(redux(reducer, initialState)))

One redux devtools connection for multiple stores

jsx
import { devtools } from 'zustand/middleware'

// Usage with a plain action store, it will log actions as "setState"
const usePlainStore1 = create(devtools((set) => ..., { name, store: storeName1 }))
const usePlainStore2 = create(devtools((set) => ..., { name, store: storeName2 }))
// Usage with a redux store, it will log full action types
const useReduxStore1 = create(devtools(redux(reducer, initialState)), { name, store: storeName3 })
const useReduxStore2 = create(devtools(redux(reducer, initialState)), { name, store: storeName4 })

Assigning different connection names will separate stores in redux devtools. This also helps group different stores into separate redux devtools connections.

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(..., {name: "MyStore"}), which will create a separate instance named "MyStore" in the devtools.

Serialize options: devtools(..., { 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:

jsx
const useBearStore = create(devtools((set) => ({
  ...
  eatFish: () => set(
    (prev) => ({ fishes: prev.fishes > 1 ? prev.fishes - 1 : 0 }),
    undefined,
    'bear/eatFish'
  ),
  ...

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

jsx
...
  addFishes: (count) => set(
    (prev) => ({ fishes: prev.fishes + count }),
    undefined,
    { type: 'bear/addFishes', count, }
  ),
  ...

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

jsx
devtools(..., { anonymousActionType: 'unknown', ... })

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

jsx
devtools(..., { enabled: false, ... })

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 the rules of hooks.

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

jsx
import { createContext, useContext } from 'react'
import { createStore, useStore } from 'zustand'

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

const StoreContext = createContext()

const App = () => (
  <StoreContext.Provider value={store}>
    ...
  </StoreContext.Provider>
)

const Component = () => {
  const store = useContext(StoreContext)
  const slice = useStore(store, selector)
  ...

TypeScript Usage

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

ts
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
import type {} from '@redux-devtools/extension' // required for devtools typing

interface BearState {
  bears: number
  increase: (by: number) => void
}

const useBearStore = create()(
  devtools(
    persist(
      (set) => ({
        bears: 0,
        increase: (by) => set((state) => ({ bears: state.bears + by })),
      }),
      {
        name: 'bear-storage',
      },
    ),
  ),
)

A more detailed TypeScript guide is here and there.

Best practices

Third-Party Libraries

Some users may want to extend Zustand's feature set which can be done using third-party libraries made by the community. For information regarding third-party libraries with Zustand, visit the doc.

Comparison with other libraries

2. Official Technical Reference & Guides (pmndrs/docs)

File: README.md


docs/getting-started/introduction.mdx

Usage

Read

sh
$ npx @pmndrs/docs                                 # the reader: every library, every page
$ npx @pmndrs/docs drei                            # straight into one
$ npx @pmndrs/docs drei/performances/instances     # straight to a page
$ npx @pmndrs/docs search instanced mesh           # one result per line, on stdout

โ†‘โ†“ drives whichever pane has the focus โ€” the list of pages, or the page itself. โŽ or โ‡ฅ
hands the focus over, esc or โ‡ฅ hands it back, and the lit border says where it is โ€” the
wheel moves whichever pane it points at, focus or no focus. โ†โ†’ changes library, b folds the sidebar away, / searches every library at once, o opens the
page in a browser, q quits. Links inside a page are clickable wherever the terminal honours
OSC 8 hyperlinks โ€” iTerm2, Ghostty, WezTerm, Kitty, Windows Terminal.

search is the half a pipe or an agent can use: results read {lib} {path} - {title}, the
shape the MCP server publishes its index in, and nothing found exits 1.
--in drei narrows to one library, --in drei/performances/instances to the matching lines of
one page.

Both read the published llms-full.txt of each library, cached for an hour under
~/.cache/pmndrs-docs โ€” --refresh fetches again. Outside a terminal, a page target is
written to stdout, so npx @pmndrs/docs drei/performances/instances | glow works.

Build

sh
$ cat foo.mdx | npx @pmndrs/docs@latest build               # one HTML fragment, on stdout
$ npx @pmndrs/docs@latest build docs out                    # one .html per .mdx, assets alongside
$ npx @pmndrs/docs@latest build docs out --format website   # the whole website, statically exported

--format fragment (the default) needs nothing but node โ€” no next build, no bundler. A
fragment is the compiled MDX and nothing else: no layout, no stylesheet, no script. Mermaid
diagrams stay fenced blocks, and Sandpack shows its code without the editor.

build --help lists every website option โ€” --libname, --base-path, --icon, --theme-*โ€ฆ Each
one falls back to the environment variable it maps to, the same ones
configuration documents.

Preview a folder of MDX, served

sh
$ curl -sL https://raw.githubusercontent.com/pmndrs/docs/refs/heads/main/preview.sh | \
  MDX="docs" \
  ICON="๐Ÿฅ‘" \
  sh

Builds the website, then serves it โ€” alongside the MDX folder itself, so relative assets
resolve while you edit. Any option from
configuration goes in the same way, and
VERSION picks a published version of the CLI.

Releasing

Every push to main redeploys docs.pmnd.rs via ci.yml โ€” no changeset needed for that.

Add one (pnpm changeset) only when downstream consumers pinning pmndrs/docs/.github/workflows/build.yml@v4 or @pmndrs/docs@4 should pull the change. It bumps package.json, publishes to npm, and tags vX.Y.Z + vX โ€” so @v4 resolves to the latest.

TL;DR โ€” site-only tweak: skip. Anything consumers see (workflow, build behavior, templates): add one.

Test

Visual tests are performed in the cloud, through chromatic.yml.

You can also replay locally:

sh
$ npx playwright test --update-snapshots
$ npx chromatic --playwright --project-token $CHROMATIC_PROJECT_TOKEN

File: Readme.md

Poimandres

bash
git clone https://github.com/pmndrs/website.git
cd website

yarn
yarn dev

File: readme.md

Poimandres

bash
git clone https://github.com/pmndrs/website.git
cd website

yarn
yarn dev

File: docs/getting-started/introduction.mdx


title: pmndrs/docs nav: 0

A static MDX documentation generator, with a GitHub reusable workflow. It is primarily used for some pmndrs/* projects, but will work for anyone.

Those projects are known to be using this generator.

INSTALL

Pre-requisites:

  • Install nvm, then:
    sh
    $ nvm install
    $ nvm use
    $ node -v # make sure your version satisfies package.json#engines.node
    nb: if you want this node version to be your default nvm's one:
    nvm alias default node
sh
$ git clone https://github.com/pmndrs/docs.git
$ cd docs
$ pnpm install

Configuration

[!IMPORTANT]

Default value is always: "" (think empty).

var description example
MDX* Path to *.mdx folderNB: can be relative or absolute docs or ~/code/myproject/documentation
NEXT_PUBLIC_LIBNAME* Library name React Three Fiber
NEXT_PUBLIC_LIBNAME_SHORT Library short name r3f
NEXT_PUBLIC_LIBNAME_DOTSUFFIX_LABEL Text for the ".docs" suffix link inside the header docs
NEXT_PUBLIC_LIBNAME_DOTSUFFIX_HREF Href for the ".docs" suffix link inside the header https://docs.pmnd.rs
BASE_PATH Base path for the final URL /react-three-fiber
DIST_DIR Path to the output folder (within project) out or docs/out/react-three-fiber
OUTPUT Set to export for static output export
HOME_REDIRECT Where the home should redirect /getting-started/introduction
MDX_BASEURL Base URL for inlining relative images http://localhost:60141or https://github.com/pmndrs/react-three-fiber/raw/master/docs
SOURCECODE_BASEURL Base URL for sourcecode: code path https://github.com/pmndrs/react-three-fiber/tree/main
EDIT_BASEURL Base URL for displaying "Edit this page" URLs https://github.com/pmndrs/react-three-fiber/edit/master/docs
NEXT_PUBLIC_URL Final URL of the published website https://pmndrs.github.io/react-three-fiber
ICON Emoji or image to use as (fav)icon (path local to MDX) ๐Ÿ‡จ๐Ÿ‡ญ or /icon.png or /favicon.ico
LOGO Logo src/path (either FQURL or local to MDX path) /logo.png or https://worldvectorlogo.com/r3f.png
GITHUB Github URL https://github.com/pmndrs/react-three-fiber
DISCORD Discord URL https://discord.com/channels/740090768164651008/740093168770613279
THEME_PRIMARY Primary accent color #323e48
THEME_SCHEME Theme scheme content or expressive or fidelity or monochrome or neutral or tonalSpot or vibrant
THEME_CONTRAST Theme contrast -- value between -1 and 1 0 or -1 or 1 or -.6
THEME_NOTE "note" color #1f6feb
THEME_TIP "tip" color #238636
THEME_IMPORTANT "important" color #8957e5
THEME_WARNING "warning" color #d29922
THEME_CAUTION "caution" color #da3633
CONTRIBUTORS_PAT GitHub token for contributors API (see: https://docs.github.com/en/rest/collaborators/collaborators?apiVersion=2022-11-28#list-repository-collaborators) ghp_1234567890

* Required

MDX_BASEURL

Given a advanced/introduction.mdx file in the MDX folder:

md

becomes (for a MDX_BASEURL=http://localhost:60141 value):

md

http://localhost:60141 being the MDX folder served.

[!TIP]
When deployed on GitHub Pages, MDX_BASEURL will typically value something like https://github.com/pmndrs/uikit/raw/main/docs, thanks to build.yml rule.

THEME_*

We implement m3 design system, using material-theme-builder.

[!NOTE]

  • Material Color for more information
  • We currently don't have secondary/tertiary colors (maybe some day).

Usage

dev

sh
$ (
  trap 'kill -9 0' SIGINT

  export _PORT=60141

  export MDX=docs
  export NEXT_PUBLIC_LIBNAME="Poimandres"
  export NEXT_PUBLIC_LIBNAME_SHORT="pmndrs"
  export NEXT_PUBLIC_LIBNAME_DOTSUFFIX_LABEL="docs"
  export NEXT_PUBLIC_LIBNAME_DOTSUFFIX_HREF="https://docs.pmnd.rs"
  export BASE_PATH=
  export DIST_DIR=
  export OUTPUT=
  export HOME_REDIRECT=
  export MDX_BASEURL=http://localhost:$_PORT
  export SOURCECODE_BASEURL="vscode://file$(pwd)"
  export EDIT_BASEURL="vscode://file$(pwd)/docs"
  export NEXT_PUBLIC_URL=
  export ICON=
  export LOGO=gutenberg.jpg
  export GITHUB=https://github.com/pmndrs/docs
  export DISCORD=https://discord.com/channels/740090768164651008/1264328004172255393
  export THEME_PRIMARY="#323e48"
  export THEME_SCHEME="tonalSpot"
  export THEME_CONTRAST="0"
  export THEME_NOTE="#1f6feb"
  export THEME_TIP="#238636"
  export THEME_IMPORTANT="#8957e5"
  export THEME_WARNING="#d29922"
  export THEME_CAUTION="#da3633"
  export CONTRIBUTORS_PAT=

  kill $(lsof -ti:"$_PORT")
  npx serve $MDX -p $_PORT --no-port-switching --no-clipboard &

  pnpm run dev &

  wait
)

Then go to: http://localhost:3000

[!TIP]
If HOME_REDIRECT= empty, / will not redirect, and instead displays an index of libraries.

build

sh
$ (
  trap 'kill -9 0' SIGINT

  rm -rf out

  export _PORT=60141

  export MDX=docs
  export NEXT_PUBLIC_LIBNAME="Poimandres"
  export NEXT_PUBLIC_LIBNAME_SHORT="pmndrs"
  export NEXT_PUBLIC_LIBNAME_DOTSUFFIX_LABEL="docs"
  export NEXT_PUBLIC_LIBNAME_DOTSUFFIX_HREF="https://docs.pmnd.rs"
  export BASE_PATH=
  export DIST_DIR=
  export OUTPUT=export
  export HOME_REDIRECT=/getting-started/introduction
  export MDX_BASEURL=http://localhost:$_PORT
  export SOURCECODE_BASEURL=
  export EDIT_BASEURL=
  export NEXT_PUBLIC_URL=
  export ICON=
  export LOGO=gutenberg.jpg
  export GITHUB=https://github.com/pmndrs/docs
  export DISCORD=https://discord.com/channels/740090768164651008/1264328004172255393
  export THEME_PRIMARY="#323e48"
  export THEME_SCHEME="tonalSpot"
  export THEME_CONTRAST="0"
  export THEME_NOTE="#1f6feb"
  export THEME_TIP="#238636"
  export THEME_IMPORTANT="#8957e5"
  export THEME_WARNING="#d29922"
  export THEME_CAUTION="#da3633"
  export CONTRIBUTORS_PAT=

  pnpm run build

  kill $(lsof -ti:"$_PORT")
  npx serve $MDX -p $_PORT --no-port-switching --no-clipboard &

  npx serve out &

  wait
)

http://localhost:3000

CLI

No clone, no install โ€” the published CLI does the same build:

sh
$ cd ~/code/pmndrs/react-three-fiber
$ (
  trap 'kill -9 0' SIGINT

  export _PORT=60141

  export NEXT_PUBLIC_LIBNAME="React Three Fiber"
  export NEXT_PUBLIC_LIBNAME_SHORT="r3f"
  export BASE_PATH=/toto
  export HOME_REDIRECT=/getting-started/introduction
  export MDX_BASEURL=http://localhost:$_PORT
  export ICON=๐Ÿ‡จ๐Ÿ‡ญ
  export GITHUB=https://github.com/pmndrs/react-three-fiber

  npx -y @pmndrs/docs@latest build docs docs/out --format website

  kill $(lsof -ti:"$_PORT")
  npx serve docs -p $_PORT --no-port-switching --no-clipboard &

  npx -y serve docs/out &

  wait
)

Then go to: http://localhost:3000

Every option above has a flag too โ€” npx @pmndrs/docs@latest build --help lists them.

Agents

llms.txt dumps and the pmndrs MCP server moved to their own page: Agents.