{"name":"zustand","private":false,"version":"4.3.7","description":"🐻 Bear necessities for state management in React","main":"./index.js","types":"./index.d.ts","typesVersions":{"<4.0":{"esm/*":["ts3.4/*"],"*":["ts3.4/*"]}},"exports":{"./package.json":"./package.json",".":{"types":"./index.d.ts","import":{"types":"./esm/index.d.mts","default":"./esm/index.mjs"},"module":"./esm/index.js","default":"./index.js"},"./vanilla":{"types":"./vanilla.d.ts","import":{"types":"./esm/vanilla.d.mts","default":"./esm/vanilla.mjs"},"module":"./esm/vanilla.js","default":"./vanilla.js"},"./middleware":{"types":"./middleware.d.ts","import":{"types":"./esm/middleware.d.mts","default":"./esm/middleware.mjs"},"module":"./esm/middleware.js","default":"./middleware.js"},"./middleware/immer":{"types":"./middleware/immer.d.ts","import":{"types":"./esm/middleware/immer.d.mts","default":"./esm/middleware/immer.mjs"},"module":"./esm/middleware/immer.js","default":"./middleware/immer.js"},"./shallow":{"types":"./shallow.d.ts","import":{"types":"./esm/shallow.d.mts","default":"./esm/shallow.mjs"},"module":"./esm/shallow.js","default":"./shallow.js"},"./context":{"types":"./context.d.ts","import":{"types":"./esm/context.d.mts","default":"./esm/context.mjs"},"module":"./esm/context.js","default":"./context.js"}},"sideEffects":false,"engines":{"node":">=12.7.0"},"repository":{"type":"git","url":"git+https://github.com/pmndrs/zustand.git"},"keywords":["react","state","manager","management","redux","store"],"author":{"name":"Paul Henschel"},"contributors":[{"name":"Jeremy Holcomb","url":"https://github.com/JeremyRH"},{"name":"Daishi Kato","url":"https://github.com/dai-shi"}],"license":"MIT","bugs":{"url":"https://github.com/pmndrs/zustand/issues"},"homepage":"https://github.com/pmndrs/zustand","dependencies":{"use-sync-external-store":"1.2.0"},"peerDependencies":{"immer":">=9.0","react":">=16.8"},"peerDependenciesMeta":{"immer":{"optional":true},"react":{"optional":true}},"gitHead":"142b60025b41ed3407c2abb08afe3f048ea6258b","_id":"zustand@4.3.7","_nodeVersion":"16.19.0","_npmVersion":"8.19.3","dist":{"integrity":"sha512-dY8ERwB9Nd21ellgkBZFhudER8KVlelZm8388B5nDAXhO/+FZDhYMuRnqDgu5SYyRgz/iaf8RKnbUs/cHfOGlQ==","shasum":"501b1f0393a7f1d103332e45ab574be5747fedce","tarball":"http://registry-npm.ywwl.com/zustand/download/zustand-4.3.7.tgz","fileCount":105,"unpackedSize":281818,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIBsPsamvB38F/H4hEq5ltriRxdEffnfz7nM1SaXUgpoWAiEAhKLItJT3f1Z5GQfBnHSNoONIV5CPG19lEewAmbUKWx4="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJkJvd4ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmpKyg//QIIEKB2aMdu9s1qvTeV5/p1cYkDSl7D2EFyKkumysKMPk1Lr\r\nkN4qHYwxPvUv+GtTbgCxBKjfaDlTSxQIAHM5JNWOaiJ9ZWQXpn3r/R0q2soL\r\nl4AUgp39wk9Uh1eKVWQBsDXfCkxcBbTxk1pCWHKxkk/fbnhGrb5DJ6nFNu32\r\nzrCQhrnCrHC/nmnPG4xbWaIZTrF2bLSXFG3WOEnYhDLYF+mTY0OzoLyv3to1\r\nWwDbUZWN17eF4j4+Xd3purZNCwZ9vhcuYuWg4EGMf4byqo3XBrksFGRZczHB\r\nxEd1rBPmT3Ti2myjMyOFV8rp+NFheSMf/WDk9MwkaU6Nq9Dd+HBoEDWesy1a\r\nFR5Wc/yn+PqaYOgo11pWMVk8F3IfKLvPoO1Yy193MAc0iBmfOAFJFlhyOvYj\r\nV33FlXzoxMIByTEAVPTUps+Qbupnw24Wn/L0x/gvFTN+8SArYC/WhtYJu+4Q\r\npYB0r13PYeE2dcj91b9D2aaTT3Hph4aoZgcKa1mI9brLK0N17edxh8qEaTR6\r\ndIErmBalWMmxf//zqZ5nvshqcu8jhhYXFA1uhMMkySIccODncdfO1eAo1QX8\r\nvgYK3i1VwD1WMAapse8qAzwzMOV/ZY6/GNDEC9fYi1e1WIkTlD+z+VOAFYmk\r\nu4bEHMmAgW8UDIP0pen+5zlL0lm8/oFsnQ4=\r\n=SUl8\r\n-----END PGP SIGNATURE-----\r\n","size":47292,"noattachment":false,"key":"/zustand/-/zustand-4.3.7.tgz"},"_npmUser":{"name":"daishi","email":"daishi@axlight.com"},"directories":{},"maintainers":[{"name":"daishi","email":"daishi@axlight.com"},{"name":"jeremyrh","email":"holcomb227@gmail.com"},{"name":"drcmda","email":"drcmda@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/zustand_4.3.7_1680275320567_0.7451527392508406"},"_hasShrinkwrap":false,"readme":"<p align=\"center\">\n  <img src=\"docs/bear.jpg\" />\n</p>\n\n[![Build Status](https://img.shields.io/github/actions/workflow/status/pmndrs/zustand/lint-and-type.yml?branch=main&style=flat&colorA=000000&colorB=000000)](https://github.com/pmndrs/zustand/actions?query=workflow%3ALint)\n[![Build Size](https://img.shields.io/bundlephobia/minzip/zustand?label=bundle%20size&style=flat&colorA=000000&colorB=000000)](https://bundlephobia.com/result?p=zustand)\n[![Version](https://img.shields.io/npm/v/zustand?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/zustand)\n[![Downloads](https://img.shields.io/npm/dt/zustand.svg?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/zustand)\n[![Discord Shield](https://img.shields.io/discord/740090768164651008?style=flat&colorA=000000&colorB=000000&label=discord&logo=discord&logoColor=ffffff)](https://discord.gg/poimandres)\n\nA small, fast and scalable bearbones state-management solution using simplified flux principles. Has a comfy API based on hooks, isn't boilerplatey or opinionated.\n\nDon'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.\n\nYou can try a live demo [here](https://githubbox.com/pmndrs/zustand/tree/main/examples/demo).\n\n```bash\nnpm i zustand\n```\n\n: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).\n\n## First create a store\n\nYour 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/guides/immutable-state-and-merging.md) to help it.\n\n```jsx\nimport { create } from 'zustand'\n\nconst useBearStore = create((set) => ({\n  bears: 0,\n  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),\n  removeAllBears: () => set({ bears: 0 }),\n}))\n```\n\n## Then bind your components, and that's it!\n\nUse the hook anywhere, no providers are needed. Select your state and the component will re-render on changes.\n\n```jsx\nfunction BearCounter() {\n  const bears = useBearStore((state) => state.bears)\n  return <h1>{bears} around here ...</h1>\n}\n\nfunction Controls() {\n  const increasePopulation = useBearStore((state) => state.increasePopulation)\n  return <button onClick={increasePopulation}>one up</button>\n}\n```\n\n### Why zustand over redux?\n\n- Simple and un-opinionated\n- Makes hooks the primary means of consuming state\n- Doesn't wrap your app in context providers\n- [Can inform components transiently (without causing render)](#transient-updates-for-often-occurring-state-changes)\n\n### Why zustand over context?\n\n- Less boilerplate\n- Renders components only on changes\n- Centralized, action-based state management\n\n---\n\n# Recipes\n\n## Fetching everything\n\nYou can, but bear in mind that it will cause the component to update on every state change!\n\n```jsx\nconst state = useBearStore()\n```\n\n## Selecting multiple state slices\n\nIt detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.\n\n```jsx\nconst nuts = useBearStore((state) => state.nuts)\nconst honey = useBearStore((state) => state.honey)\n```\n\nIf you want to construct a single object with multiple state-picks inside, similar to redux's mapStateToProps, you can use [useShallow](./docs/guides/prevent-rerenders-with-use-shallow.md) to prevent unnecessary rerenders when the selector output does not change according to shallow equal.\n\n```jsx\nimport { create } from 'zustand'\nimport { useShallow } from 'zustand/react/shallow'\n\nconst useBearStore = create((set) => ({\n  nuts: 0,\n  honey: 0,\n  treats: {},\n  // ...\n}))\n\n// Object pick, re-renders the component when either state.nuts or state.honey change\nconst { nuts, honey } = useBearStore(\n  useShallow((state) => ({ nuts: state.nuts, honey: state.honey })),\n)\n\n// Array pick, re-renders the component when either state.nuts or state.honey change\nconst [nuts, honey] = useBearStore(\n  useShallow((state) => [state.nuts, state.honey]),\n)\n\n// Mapped picks, re-renders the component when state.treats changes in order, count or keys\nconst treats = useBearStore(useShallow((state) => Object.keys(state.treats)))\n```\n\nFor more control over re-rendering, you may provide any custom equality function (this example requires the use of [`createWithEqualityFn`](./docs/migrations/migrating-to-v5.md#using-custom-equality-functions-such-as-shallow)).\n\n```jsx\nconst treats = useBearStore(\n  (state) => state.treats,\n  (oldTreats, newTreats) => compare(oldTreats, newTreats),\n)\n```\n\n## Overwriting state\n\nThe `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.\n\n```jsx\nimport omit from 'lodash-es/omit'\n\nconst useFishStore = create((set) => ({\n  salmon: 1,\n  tuna: 2,\n  deleteEverything: () => set({}, true), // clears the entire store, actions included\n  deleteTuna: () => set((state) => omit(state, ['tuna']), true),\n}))\n```\n\n## Async actions\n\nJust call `set` when you're ready, zustand doesn't care if your actions are async or not.\n\n```jsx\nconst useFishStore = create((set) => ({\n  fishies: {},\n  fetch: async (pond) => {\n    const response = await fetch(pond)\n    set({ fishies: await response.json() })\n  },\n}))\n```\n\n## Read from state in actions\n\n`set` allows fn-updates `set(state => result)`, but you still have access to state outside of it through `get`.\n\n```jsx\nconst useSoundStore = create((set, get) => ({\n  sound: 'grunt',\n  action: () => {\n    const sound = get().sound\n    ...\n```\n\n## Reading/writing state and reacting to changes outside of components\n\nSometimes 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.\n\n: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).\n\n```jsx\nconst useDogStore = create(() => ({ paw: true, snout: true, fur: true }))\n\n// Getting non-reactive fresh state\nconst paw = useDogStore.getState().paw\n// Listening to all changes, fires synchronously on every change\nconst unsub1 = useDogStore.subscribe(console.log)\n// Updating state, will trigger listeners\nuseDogStore.setState({ paw: false })\n// Unsubscribe listeners\nunsub1()\n\n// You can of course use the hook as you always would\nfunction Component() {\n  const paw = useDogStore((state) => state.paw)\n  ...\n```\n\n### Using subscribe with selector\n\nIf you need to subscribe with a selector,\n`subscribeWithSelector` middleware will help.\n\nWith this middleware `subscribe` accepts an additional signature:\n\n```ts\nsubscribe(selector, callback, options?: { equalityFn, fireImmediately }): Unsubscribe\n```\n\n```js\nimport { subscribeWithSelector } from 'zustand/middleware'\nconst useDogStore = create(\n  subscribeWithSelector(() => ({ paw: true, snout: true, fur: true })),\n)\n\n// Listening to selected changes, in this case when \"paw\" changes\nconst unsub2 = useDogStore.subscribe((state) => state.paw, console.log)\n// Subscribe also exposes the previous value\nconst unsub3 = useDogStore.subscribe(\n  (state) => state.paw,\n  (paw, previousPaw) => console.log(paw, previousPaw),\n)\n// Subscribe also supports an optional equality function\nconst unsub4 = useDogStore.subscribe(\n  (state) => [state.paw, state.fur],\n  console.log,\n  { equalityFn: shallow },\n)\n// Subscribe and fire immediately\nconst unsub5 = useDogStore.subscribe((state) => state.paw, console.log, {\n  fireImmediately: true,\n})\n```\n\n## Using zustand without React\n\nZustand 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.\n\n```jsx\nimport { createStore } from 'zustand/vanilla'\n\nconst store = createStore((set) => ...)\nconst { getState, setState, subscribe, getInitialState } = store\n\nexport default store\n```\n\nYou can use a vanilla store with `useStore` hook available since v4.\n\n```jsx\nimport { useStore } from 'zustand'\nimport { vanillaStore } from './vanillaStore'\n\nconst useBoundStore = (selector) => useStore(vanillaStore, selector)\n```\n\n:warning: Note that middlewares that modify `set` or `get` are not applied to `getState` and `setState`.\n\n## Transient updates (for often occurring state-changes)\n\nThe 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.\n\n```jsx\nconst useScratchStore = create((set) => ({ scratches: 0, ... }))\n\nconst Component = () => {\n  // Fetch initial state\n  const scratchRef = useRef(useScratchStore.getState().scratches)\n  // Connect to the store on mount, disconnect on unmount, catch state-changes in a reference\n  useEffect(() => useScratchStore.subscribe(\n    state => (scratchRef.current = state.scratches)\n  ), [])\n  ...\n```\n\n## Sick of reducers and changing nested states? Use Immer!\n\nReducing nested structures is tiresome. Have you tried [immer](https://github.com/mweststrate/immer)?\n\n```jsx\nimport { produce } from 'immer'\n\nconst useLushStore = create((set) => ({\n  lush: { forest: { contains: { a: 'bear' } } },\n  clearForest: () =>\n    set(\n      produce((state) => {\n        state.lush.forest.contains = null\n      }),\n    ),\n}))\n\nconst clearForest = useLushStore((state) => state.clearForest)\nclearForest()\n```\n\n[Alternatively, there are some other solutions.](./docs/guides/updating-state.md#with-immer)\n\n## Persist middleware\n\nYou can persist your store's data using any kind of storage.\n\n```jsx\nimport { create } from 'zustand'\nimport { persist, createJSONStorage } from 'zustand/middleware'\n\nconst useFishStore = create(\n  persist(\n    (set, get) => ({\n      fishes: 0,\n      addAFish: () => set({ fishes: get().fishes + 1 }),\n    }),\n    {\n      name: 'food-storage', // name of the item in the storage (must be unique)\n      storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used\n    },\n  ),\n)\n```\n\n[See the full documentation for this middleware.](./docs/integrations/persisting-store-data.md)\n\n## Immer middleware\n\nImmer is available as middleware too.\n\n```jsx\nimport { create } from 'zustand'\nimport { immer } from 'zustand/middleware/immer'\n\nconst useBeeStore = create(\n  immer((set) => ({\n    bees: 0,\n    addBees: (by) =>\n      set((state) => {\n        state.bees += by\n      }),\n  })),\n)\n```\n\n## Can't live without redux-like reducers and action types?\n\n```jsx\nconst types = { increase: 'INCREASE', decrease: 'DECREASE' }\n\nconst reducer = (state, { type, by = 1 }) => {\n  switch (type) {\n    case types.increase:\n      return { grumpiness: state.grumpiness + by }\n    case types.decrease:\n      return { grumpiness: state.grumpiness - by }\n  }\n}\n\nconst useGrumpyStore = create((set) => ({\n  grumpiness: 0,\n  dispatch: (args) => set((state) => reducer(state, args)),\n}))\n\nconst dispatch = useGrumpyStore((state) => state.dispatch)\ndispatch({ type: types.increase, by: 2 })\n```\n\nOr, 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.\n\n```jsx\nimport { redux } from 'zustand/middleware'\n\nconst useGrumpyStore = create(redux(reducer, initialState))\n```\n\n## Redux devtools\n\nInstall the [Redux DevTools Chrome extension](https://chromewebstore.google.com/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd) to use the devtools middleware.\n\n```jsx\nimport { devtools } from 'zustand/middleware'\n\n// Usage with a plain action store, it will log actions as \"setState\"\nconst usePlainStore = create(devtools((set) => ...))\n// Usage with a redux store, it will log full action types\nconst useReduxStore = create(devtools(redux(reducer, initialState)))\n```\n\nOne redux devtools connection for multiple stores\n\n```jsx\nimport { devtools } from 'zustand/middleware'\n\n// Usage with a plain action store, it will log actions as \"setState\"\nconst usePlainStore1 = create(devtools((set) => ..., { name, store: storeName1 }))\nconst usePlainStore2 = create(devtools((set) => ..., { name, store: storeName2 }))\n// Usage with a redux store, it will log full action types\nconst useReduxStore = create(devtools(redux(reducer, initialState)), , { name, store: storeName3 })\nconst useReduxStore = create(devtools(redux(reducer, initialState)), , { name, store: storeName4 })\n```\n\nAssigning different connection names will separate stores in redux devtools. This also helps group different stores into separate redux devtools connections.\n\ndevtools 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.\n\nName store: `devtools(..., {name: \"MyStore\"})`, which will create a separate instance named \"MyStore\" in the devtools.\n\nSerialize options: `devtools(..., { serialize: { options: true } })`.\n\n#### Logging Actions\n\ndevtools 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\n\nYou can log a specific action type for each `set` function by passing a third parameter:\n\n```jsx\nconst useBearStore = create(devtools((set) => ({\n  ...\n  eatFish: () => set(\n    (prev) => ({ fishes: prev.fishes > 1 ? prev.fishes - 1 : 0 }),\n    undefined,\n    'bear/eatFish'\n  ),\n  ...\n```\n\nYou can also log the action's type along with its payload:\n\n```jsx\n  ...\n  addFishes: (count) => set(\n    (prev) => ({ fishes: prev.fishes + count }),\n    undefined,\n    { type: 'bear/addFishes', count, }\n  ),\n  ...\n```\n\nIf an action type is not provided, it is defaulted to \"anonymous\". You can customize this default value by providing an `anonymousActionType` parameter:\n\n```jsx\ndevtools(..., { anonymousActionType: 'unknown', ... })\n```\n\nIf you wish to disable devtools (on production for instance). You can customize this setting by providing the `enabled` parameter:\n\n```jsx\ndevtools(..., { enabled: false, ... })\n```\n\n## React context\n\nThe 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.\n\nThe recommended method available since v4 is to use the vanilla store.\n\n```jsx\nimport { createContext, useContext } from 'react'\nimport { createStore, useStore } from 'zustand'\n\nconst store = createStore(...) // vanilla store without hooks\n\nconst StoreContext = createContext()\n\nconst App = () => (\n  <StoreContext.Provider value={store}>\n    ...\n  </StoreContext.Provider>\n)\n\nconst Component = () => {\n  const store = useContext(StoreContext)\n  const slice = useStore(store, selector)\n  ...\n```\n\n## TypeScript Usage\n\nBasic typescript usage doesn't require anything special except for writing `create<State>()(...)` instead of `create(...)`...\n\n```ts\nimport { create } from 'zustand'\nimport { devtools, persist } from 'zustand/middleware'\nimport type {} from '@redux-devtools/extension' // required for devtools typing\n\ninterface BearState {\n  bears: number\n  increase: (by: number) => void\n}\n\nconst useBearStore = create<BearState>()(\n  devtools(\n    persist(\n      (set) => ({\n        bears: 0,\n        increase: (by) => set((state) => ({ bears: state.bears + by })),\n      }),\n      {\n        name: 'bear-storage',\n      },\n    ),\n  ),\n)\n```\n\nA more complete TypeScript guide is [here](docs/guides/typescript.md).\n\n## Best practices\n\n- You may wonder how to organize your code for better maintenance: [Splitting the store into separate slices](./docs/guides/slices-pattern.md).\n- Recommended usage for this unopinionated library: [Flux inspired practice](./docs/guides/flux-inspired-practice.md).\n- [Calling actions outside a React event handler in pre-React 18](./docs/guides/event-handler-in-pre-react-18.md).\n- [Testing](./docs/guides/testing.md)\n- For more, have a look [in the docs folder](./docs/)\n\n## Third-Party Libraries\n\nSome 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/integrations/third-party-libraries.md).\n\n## Comparison with other libraries\n\n- [Difference between zustand and other state management libraries for React](https://docs.pmnd.rs/zustand/getting-started/comparison)\n","publish_time":1680275320809,"_cnpm_publish_time":1680275320809,"dist-tags":{"latest":"5.1.0"}}