Skip to content
Myr

README.md

This file

Path

README.md

512 lines · 17.4 KiB · Markdown

Last changed by

docs: fix broken migrating-to-v5 link in README (#3567)Daishi Katobefore adoptionea612a5

History of this file

Take it

The walk stopped after 200 commits: lines older than f85898f point at it.

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

line 1why, one step back
1<p align="center">

Fix README internal links for GitHub rendering (#3403)Copilotbefore adoptionda381c3

line 2why, one step back
2 <img src="./docs/bear.jpg" />

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 3–4why, one step back
3</p>
4

docs: fix README actions link for build status badge (#3378)Pavan Shindebefore adoptionb7d2932

line 5why, one step back
5[![Build Status](https://img.shields.io/github/actions/workflow/status/pmndrs/zustand/test.yml?branch=main&style=flat&colorA=000000&colorB=000000)](https://github.com/pmndrs/zustand/actions?query=workflow%3ATest)

docs: update badge (#3181)Danilo Brittobefore adoption1b7eb69

line 6why, one step back
6[![Build Size](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fdeno.bundlejs.com%2F%3Fq%3Dzustand&query=%24.size.uncompressedSize&style=flat&label=bundle%20size&colorA=000000&colorB=000000)](https://bundlejs.com/?q=zustand)

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 7–10why, one step back
7[![Version](https://img.shields.io/npm/v/zustand?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/zustand)
8[![Downloads](https://img.shields.io/npm/dt/zustand.svg?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/zustand)9[![Discord Shield](https://img.shields.io/discord/740090768164651008?style=flat&colorA=000000&colorB=000000&label=discord&logo=discord&logoColor=ffffff)](https://discord.gg/poimandres)10

Update READMEDaishi Katobefore adoption957bf89

lines 11–16why, one step back
11<a href="https://dai-shi.github.io/zustand-banner-sponsorship/sponsors/" target="_blank" rel="noopener">
12 <p align="center">13 <img src="https://dai-shi.github.io/zustand-banner-sponsorship/api/banner.png" />14 </p>15</a>16

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 17–20why, one step back
17A small, fast and scalable bearbones state-management solution using simplified flux principles. Has a comfy API based on hooks, isn't boilerplatey or opinionated.
1819Don'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](https://react-redux.js.org/api/hooks#stale-props-and-zombie-children), [react concurrency](https://github.com/bvaughn/rfcs/blob/useMutableSource/text/0000-use-mutable-source.md), and [context loss](https://github.com/facebook/react/issues/13332) between mixed renderers. It may be the one state-manager in the React space that gets all of these right.20

fix links to the demo and the docs (#3148)Daishi Katobefore adoption3d9ecb1

line 21why, one step back
21You can try a live [demo](https://zustand-demo.pmnd.rs/) and read the [docs](https://zustand.docs.pmnd.rs/).

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 22–30why, one step back
22
23```bash24npm install zustand25```2627:warning: This readme is written for JavaScript users. If you are a TypeScript user, be sure to check out our [TypeScript Usage section](#typescript-usage).2829## First create a store30

fix: update broken README links from docs/guides/ to docs/learn/guides/ (#3542)Copilotbefore adoptionbeca84e

line 31why, one step back
31Your 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](./docs/learn/guides/immutable-state-and-merging.md) to help it.

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 32–92why, one step back
32
33```jsx34import { create } from 'zustand'3536const useBearStore = create((set) => ({37 bears: 0,38 increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),39 removeAllBears: () => set({ bears: 0 }),40}))41```4243## Then bind your components, and that's it!4445Use the hook anywhere, no providers are needed. Select your state and the component will re-render on changes.4647```jsx48function BearCounter() {49 const bears = useBearStore((state) => state.bears)50 return <h1>{bears} around here ...</h1>51}5253function Controls() {54 const increasePopulation = useBearStore((state) => state.increasePopulation)55 return <button onClick={increasePopulation}>one up</button>56}57```5859### Why zustand over redux?6061- Simple and un-opinionated62- Makes hooks the primary means of consuming state63- Doesn't wrap your app in context providers64- [Can inform components transiently (without causing render)](#transient-updates-for-often-occurring-state-changes)6566### Why zustand over context?6768- Less boilerplate69- Renders components only on changes70- Centralized, action-based state management7172---7374# Recipes7576## Fetching everything7778You can, but bear in mind that it will cause the component to update on every state change!7980```jsx81const state = useBearStore()82```8384## Selecting multiple state slices8586It detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.8788```jsx89const nuts = useBearStore((state) => state.nuts)90const honey = useBearStore((state) => state.honey)91```92

fix: update broken README links from docs/guides/ to docs/learn/guides/ (#3542)Copilotbefore adoptionbeca84e

line 93why, one step back
93If you want to construct a single object with multiple state-picks inside, similar to redux's mapStateToProps, you can use [useShallow](./docs/learn/guides/prevent-rerenders-with-use-shallow.md) to prevent unnecessary rerenders when the selector output does not change according to shallow equal.

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 94–119why, one step back
94
95```jsx96import { create } from 'zustand'97import { useShallow } from 'zustand/react/shallow'9899const useBearStore = create((set) => ({100 nuts: 0,101 honey: 0,102 treats: {},103 // ...104}))105106// Object pick, re-renders the component when either state.nuts or state.honey change107const { nuts, honey } = useBearStore(108 useShallow((state) => ({ nuts: state.nuts, honey: state.honey })),109)110111// Array pick, re-renders the component when either state.nuts or state.honey change112const [nuts, honey] = useBearStore(113 useShallow((state) => [state.nuts, state.honey]),114)115116// Mapped picks, re-renders the component when state.treats changes in order, count or keys117const treats = useBearStore(useShallow((state) => Object.keys(state.treats)))118```119

docs: fix broken migrating-to-v5 link in README (#3567)Daishi Katobefore adoptionea612a5

line 120why, one step back
120For more control over re-rendering, you may provide any custom equality function (this example requires the use of [`createWithEqualityFn`](./docs/reference/migrations/migrating-to-v5.md#using-custom-equality-functions-such-as-shallow)).

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 121–137why, one step back
121
122```jsx123const treats = useBearStore(124 (state) => state.treats,125 (oldTreats, newTreats) => compare(oldTreats, newTreats),126)127```128129## Overwriting state130131The `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.132133```jsx134const useFishStore = create((set) => ({135 salmon: 1,136 tuna: 2,137 deleteEverything: () => set({}, true), // clears the entire store, actions included

docs(README): remove 'omit' in 'Overwriting state' section (#3160)Wonsuk Choibefore adoptione639587

line 138why, one step back
138 deleteTuna: () => set(({ tuna, ...rest }) => rest, true),

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 139–289why, one step back
139}))
140```141142## Async actions143144Just call `set` when you're ready, zustand doesn't care if your actions are async or not.145146```jsx147const useFishStore = create((set) => ({148 fishies: {},149 fetch: async (pond) => {150 const response = await fetch(pond)151 set({ fishies: await response.json() })152 },153}))154```155156## Read from state in actions157158`set` allows fn-updates `set(state => result)`, but you still have access to state outside of it through `get`.159160```jsx161const useSoundStore = create((set, get) => ({162 sound: 'grunt',163 action: () => {164 const sound = get().sound165 ...166```167168## Reading/writing state and reacting to changes outside of components169170Sometimes 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.171172:warning: This technique is not recommended for adding state in [React Server Components](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md) (typically in Next.js 13 and above). It can lead to unexpected bugs and privacy issues for your users. For more details, see [#2200](https://github.com/pmndrs/zustand/discussions/2200).173174```jsx175const useDogStore = create(() => ({ paw: true, snout: true, fur: true }))176177// Getting non-reactive fresh state178const paw = useDogStore.getState().paw179// Listening to all changes, fires synchronously on every change180const unsub1 = useDogStore.subscribe(console.log)181// Updating state, will trigger listeners182useDogStore.setState({ paw: false })183// Unsubscribe listeners184unsub1()185186// You can of course use the hook as you always would187function Component() {188 const paw = useDogStore((state) => state.paw)189 ...190```191192### Using subscribe with selector193194If you need to subscribe with a selector,195`subscribeWithSelector` middleware will help.196197With this middleware `subscribe` accepts an additional signature:198199```ts200subscribe(selector, callback, options?: { equalityFn, fireImmediately }): Unsubscribe201```202203```js204import { subscribeWithSelector } from 'zustand/middleware'205const useDogStore = create(206 subscribeWithSelector(() => ({ paw: true, snout: true, fur: true })),207)208209// Listening to selected changes, in this case when "paw" changes210const unsub2 = useDogStore.subscribe((state) => state.paw, console.log)211// Subscribe also exposes the previous value212const unsub3 = useDogStore.subscribe(213 (state) => state.paw,214 (paw, previousPaw) => console.log(paw, previousPaw),215)216// Subscribe also supports an optional equality function217const unsub4 = useDogStore.subscribe(218 (state) => [state.paw, state.fur],219 console.log,220 { equalityFn: shallow },221)222// Subscribe and fire immediately223const unsub5 = useDogStore.subscribe((state) => state.paw, console.log, {224 fireImmediately: true,225})226```227228## Using zustand without React229230Zustand 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.231232```jsx233import { createStore } from 'zustand/vanilla'234235const store = createStore((set) => ...)236const { getState, setState, subscribe, getInitialState } = store237238export default store239```240241You can use a vanilla store with `useStore` hook available since v4.242243```jsx244import { useStore } from 'zustand'245import { vanillaStore } from './vanillaStore'246247const useBoundStore = (selector) => useStore(vanillaStore, selector)248```249250:warning: Note that middlewares that modify `set` or `get` are not applied to `getState` and `setState`.251252## Transient updates (for often occurring state-changes)253254The 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](https://codesandbox.io/s/peaceful-johnson-txtws) performance impact when you are allowed to mutate the view directly.255256```jsx257const useScratchStore = create((set) => ({ scratches: 0, ... }))258259const Component = () => {260 // Fetch initial state261 const scratchRef = useRef(useScratchStore.getState().scratches)262 // Connect to the store on mount, disconnect on unmount, catch state-changes in a reference263 useEffect(() => useScratchStore.subscribe(264 state => (scratchRef.current = state.scratches)265 ), [])266 ...267```268269## Sick of reducers and changing nested states? Use Immer!270271Reducing nested structures is tiresome. Have you tried [immer](https://github.com/mweststrate/immer)?272273```jsx274import { produce } from 'immer'275276const useLushStore = create((set) => ({277 lush: { forest: { contains: { a: 'bear' } } },278 clearForest: () =>279 set(280 produce((state) => {281 state.lush.forest.contains = null282 }),283 ),284}))285286const clearForest = useLushStore((state) => state.clearForest)287clearForest()288```289

Fix dead link in README.md: update immer guide path (#3519)Copilotbefore adoption566b5bf

line 290why, one step back
290[Alternatively, there are some other solutions.](./docs/learn/guides/updating-state.md#with-immer)

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 291–313why, one step back
291
292## Persist middleware293294You can persist your store's data using any kind of storage.295296```jsx297import { create } from 'zustand'298import { persist, createJSONStorage } from 'zustand/middleware'299300const useFishStore = create(301 persist(302 (set, get) => ({303 fishes: 0,304 addAFish: () => set({ fishes: get().fishes + 1 }),305 }),306 {307 name: 'food-storage', // name of the item in the storage (must be unique)308 storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used309 },310 ),311)312```313

fix persist documentation link (#3401)wallzerobefore adoption0d250b3

line 314why, one step back
314[See the full documentation for this middleware.](./docs/reference/integrations/persisting-store-data.md)

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 315–387why, one step back
315
316## Immer middleware317318Immer is available as middleware too.319320```jsx321import { create } from 'zustand'322import { immer } from 'zustand/middleware/immer'323324const useBeeStore = create(325 immer((set) => ({326 bees: 0,327 addBees: (by) =>328 set((state) => {329 state.bees += by330 }),331 })),332)333```334335## Can't live without redux-like reducers and action types?336337```jsx338const types = { increase: 'INCREASE', decrease: 'DECREASE' }339340const reducer = (state, { type, by = 1 }) => {341 switch (type) {342 case types.increase:343 return { grumpiness: state.grumpiness + by }344 case types.decrease:345 return { grumpiness: state.grumpiness - by }346 }347}348349const useGrumpyStore = create((set) => ({350 grumpiness: 0,351 dispatch: (args) => set((state) => reducer(state, args)),352}))353354const dispatch = useGrumpyStore((state) => state.dispatch)355dispatch({ type: types.increase, by: 2 })356```357358Or, 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.359360```jsx361import { redux } from 'zustand/middleware'362363const useGrumpyStore = create(redux(reducer, initialState))364```365366## Redux devtools367368Install the [Redux DevTools Chrome extension](https://chromewebstore.google.com/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd) to use the devtools middleware.369370```jsx371import { devtools } from 'zustand/middleware'372373// Usage with a plain action store, it will log actions as "setState"374const usePlainStore = create(devtools((set) => ...))375// Usage with a redux store, it will log full action types376const useReduxStore = create(devtools(redux(reducer, initialState)))377```378379One redux devtools connection for multiple stores380381```jsx382import { devtools } from 'zustand/middleware'383384// Usage with a plain action store, it will log actions as "setState"385const usePlainStore1 = create(devtools((set) => ..., { name, store: storeName1 }))386const usePlainStore2 = create(devtools((set) => ..., { name, store: storeName2 }))387// Usage with a redux store, it will log full action types

Fix small issue in README.md (#3106)Josh Schneiderbefore adoption95bce2f

lines 388–389why, one step back
388const useReduxStore1 = create(devtools(redux(reducer, initialState)), { name, store: storeName3 })
389const useReduxStore2 = create(devtools(redux(reducer, initialState)), { name, store: storeName4 })

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 390–495why, one step back
390```
391392Assigning different connection names will separate stores in redux devtools. This also helps group different stores into separate redux devtools connections.393394devtools takes the store function as its first argument, optionally you can name the store or configure [serialize](https://github.com/zalmoxisus/redux-devtools-extension/blob/master/docs/API/Arguments.md#serialize) options with a second argument.395396Name store: `devtools(..., {name: "MyStore"})`, which will create a separate instance named "MyStore" in the devtools.397398Serialize options: `devtools(..., { serialize: { options: true } })`.399400#### Logging Actions401402devtools 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/163403404You can log a specific action type for each `set` function by passing a third parameter:405406```jsx407const useBearStore = create(devtools((set) => ({408 ...409 eatFish: () => set(410 (prev) => ({ fishes: prev.fishes > 1 ? prev.fishes - 1 : 0 }),411 undefined,412 'bear/eatFish'413 ),414 ...415```416417You can also log the action's type along with its payload:418419```jsx420 ...421 addFishes: (count) => set(422 (prev) => ({ fishes: prev.fishes + count }),423 undefined,424 { type: 'bear/addFishes', count, }425 ),426 ...427```428429If an action type is not provided, it is defaulted to "anonymous". You can customize this default value by providing an `anonymousActionType` parameter:430431```jsx432devtools(..., { anonymousActionType: 'unknown', ... })433```434435If you wish to disable devtools (on production for instance). You can customize this setting by providing the `enabled` parameter:436437```jsx438devtools(..., { enabled: false, ... })439```440441## React context442443The 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.444445The recommended method available since v4 is to use the vanilla store.446447```jsx448import { createContext, useContext } from 'react'449import { createStore, useStore } from 'zustand'450451const store = createStore(...) // vanilla store without hooks452453const StoreContext = createContext()454455const App = () => (456 <StoreContext.Provider value={store}>457 ...458 </StoreContext.Provider>459)460461const Component = () => {462 const store = useContext(StoreContext)463 const slice = useStore(store, selector)464 ...465```466467## TypeScript Usage468469Basic typescript usage doesn't require anything special except for writing `create<State>()(...)` instead of `create(...)`...470471```ts472import { create } from 'zustand'473import { devtools, persist } from 'zustand/middleware'474import type {} from '@redux-devtools/extension' // required for devtools typing475476interface BearState {477 bears: number478 increase: (by: number) => void479}480481const useBearStore = create<BearState>()(482 devtools(483 persist(484 (set) => ({485 bears: 0,486 increase: (by) => set((state) => ({ bears: state.bears + by })),487 }),488 {489 name: 'bear-storage',490 },491 ),492 ),493)494```495

Update TypeScript guide links in README.md (#3466)Felix Ecklbefore adoption3201328

line 496why, one step back
496A more detailed TypeScript guide is [here](docs/learn/guides/beginner-typescript.md) and [there](docs/learn/guides/advanced-typescript.md).

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 497–499why, one step back
497
498## Best practices499

fix(readme): best practices docs references (#3400)Aravindsreenibefore adoptiond2c72d5

lines 500–503why, one step back
500- You may wonder how to organize your code for better maintenance: [Splitting the store into separate slices](./docs/learn/guides/slices-pattern.md).
501- Recommended usage for this unopinionated library: [Flux inspired practice](./docs/learn/guides/flux-inspired-practice.md).502- [Calling actions outside a React event handler in pre-React 18](./docs/learn/guides/event-handler-in-pre-react-18.md).503- [Testing](./docs/learn/guides/testing.md)

Fix README internal links for GitHub rendering (#3403)Copilotbefore adoptionda381c3

line 504why, one step back
504- For more, have a look [in the docs folder](./docs/index.md)

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 505–507why, one step back
505
506## Third-Party Libraries507

Fix README internal links for GitHub rendering (#3403)Copilotbefore adoptionda381c3

line 508why, one step back
508Some 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](./docs/reference/integrations/third-party-libraries.md).

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 509–511why, one step back
509
510## Comparison with other libraries511

fix(readme) : comparison documentaion link (#3405)chaesunbakbefore adoption4966a15

line 512why, one step back
512- [Difference between zustand and other state management libraries for React](https://zustand.docs.pmnd.rs/learn/getting-started/comparison)