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 fileTake it
1<p align="center">2 <img src="./docs/bear.jpg" />3</p>45[](https://github.com/pmndrs/zustand/actions?query=workflow%3ATest)6[](https://bundlejs.com/?q=zustand)7[](https://www.npmjs.com/package/zustand)8[](https://www.npmjs.com/package/zustand)9[](https://discord.gg/poimandres)1011<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>1617A 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.2021You can try a live [demo](https://zustand-demo.pmnd.rs/) and read the [docs](https://zustand.docs.pmnd.rs/).2223```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 store3031Your 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.3233```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```9293If 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.9495```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```119120For 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)).121122```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 included138 deleteTuna: () => set(({ tuna, ...rest }) => rest, true),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```289290[Alternatively, there are some other solutions.](./docs/learn/guides/updating-state.md#with-immer)291292## 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```313314[See the full documentation for this middleware.](./docs/reference/integrations/persisting-store-data.md)315316## 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 types388const useReduxStore1 = create(devtools(redux(reducer, initialState)), { name, store: storeName3 })389const useReduxStore2 = create(devtools(redux(reducer, initialState)), { name, store: storeName4 })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```495496A more detailed TypeScript guide is [here](docs/learn/guides/beginner-typescript.md) and [there](docs/learn/guides/advanced-typescript.md).497498## Best practices499500- 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)504- For more, have a look [in the docs folder](./docs/index.md)505506## Third-Party Libraries507508Some 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).509510## Comparison with other libraries511512- [Difference between zustand and other state management libraries for React](https://zustand.docs.pmnd.rs/learn/getting-started/comparison)