{"id":15314315,"url":"https://github.com/barelyhuman/zustand","last_synced_at":"2025-10-09T00:30:41.559Z","repository":{"id":47138751,"uuid":"382745960","full_name":"barelyhuman/zustand","owner":"barelyhuman","description":"🐻 Bear necessities for state management in React","archived":false,"fork":true,"pushed_at":"2023-04-21T03:17:48.000Z","size":6396,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-10-02T08:45:02.056Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://zustand.surge.sh","language":"TypeScript","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"pmndrs/zustand","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/barelyhuman.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":["dai-shi"],"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"lfx_crowdfunding":null,"custom":["https://daishi.gumroad.com/l/uaxms"]}},"created_at":"2021-07-04T02:25:59.000Z","updated_at":"2023-07-30T11:24:54.000Z","dependencies_parsed_at":"2023-02-13T23:16:37.699Z","dependency_job_id":null,"html_url":"https://github.com/barelyhuman/zustand","commit_stats":null,"previous_names":[],"tags_count":47,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/barelyhuman%2Fzustand","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/barelyhuman%2Fzustand/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/barelyhuman%2Fzustand/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/barelyhuman%2Fzustand/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/barelyhuman","download_url":"https://codeload.github.com/barelyhuman/zustand/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":235775523,"owners_count":19043180,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-01T08:45:02.903Z","updated_at":"2025-10-09T00:30:36.198Z","avatar_url":"https://github.com/barelyhuman.png","language":"TypeScript","funding_links":["https://github.com/sponsors/dai-shi","https://daishi.gumroad.com/l/uaxms"],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg src=\"bear.jpg\" /\u003e\n\u003c/p\u003e\n\n[![Build Status](https://img.shields.io/github/actions/workflow/status/pmndrs/zustand/lint-and-type.yml?branch=main\u0026style=flat\u0026colorA=000000\u0026colorB=000000)](https://github.com/pmndrs/zustand/actions?query=workflow%3ALint)\n[![Build Size](https://img.shields.io/bundlephobia/minzip/zustand?label=bundle%20size\u0026style=flat\u0026colorA=000000\u0026colorB=000000)](https://bundlephobia.com/result?p=zustand)\n[![Version](https://img.shields.io/npm/v/zustand?style=flat\u0026colorA=000000\u0026colorB=000000)](https://www.npmjs.com/package/zustand)\n[![Downloads](https://img.shields.io/npm/dt/zustand.svg?style=flat\u0026colorA=000000\u0026colorB=000000)](https://www.npmjs.com/package/zustand)\n[![Discord Shield](https://img.shields.io/discord/740090768164651008?style=flat\u0026colorA=000000\u0026colorB=000000\u0026label=discord\u0026logo=discord\u0026logoColor=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 install zustand # or yarn add zustand\n```\n\n:warning: This readme is written for JavaScript users. If you are a TypeScript user, don't miss [TypeScript Usage](#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) =\u003e ({\n  bears: 0,\n  increasePopulation: () =\u003e set((state) =\u003e ({ bears: state.bears + 1 })),\n  removeAllBears: () =\u003e 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) =\u003e state.bears)\n  return \u003ch1\u003e{bears} around here ...\u003c/h1\u003e\n}\n\nfunction Controls() {\n  const increasePopulation = useBearStore((state) =\u003e state.increasePopulation)\n  return \u003cbutton onClick={increasePopulation}\u003eone up\u003c/button\u003e\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) =\u003e state.nuts)\nconst honey = useBearStore((state) =\u003e state.honey)\n```\n\nIf 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.\n\n```jsx\nimport { shallow } from 'zustand/shallow'\n\n// Object pick, re-renders the component when either state.nuts or state.honey change\nconst { nuts, honey } = useBearStore(\n  (state) =\u003e ({ nuts: state.nuts, honey: state.honey }),\n  shallow\n)\n\n// Array pick, re-renders the component when either state.nuts or state.honey change\nconst [nuts, honey] = useBearStore(\n  (state) =\u003e [state.nuts, state.honey],\n  shallow\n)\n\n// Mapped picks, re-renders the component when state.treats changes in order, count or keys\nconst treats = useBearStore((state) =\u003e Object.keys(state.treats), shallow)\n```\n\nFor more control over re-rendering, you may provide any custom equality function.\n\n```jsx\nconst treats = useBearStore(\n  (state) =\u003e state.treats,\n  (oldTreats, newTreats) =\u003e 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) =\u003e ({\n  salmon: 1,\n  tuna: 2,\n  deleteEverything: () =\u003e set({}, true), // clears the entire store, actions included\n  deleteTuna: () =\u003e set((state) =\u003e 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) =\u003e ({\n  fishies: {},\n  fetch: async (pond) =\u003e {\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 =\u003e result)`, but you still have access to state outside of it through `get`.\n\n```jsx\nconst useSoundStore = create((set, get) =\u003e ({\n  sound: \"grunt\",\n  action: () =\u003e {\n    const sound = get().sound\n    // ...\n  }\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```jsx\nconst useDogStore = create(() =\u003e ({ 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\nconst Component = () =\u003e {\n  const paw = useDogStore((state) =\u003e state.paw)\n  ...\n```\n\n### Using subscribe with selector\n\nIf you need to subscribe with 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(() =\u003e ({ paw: true, snout: true, fur: true }))\n)\n\n// Listening to selected changes, in this case when \"paw\" changes\nconst unsub2 = useDogStore.subscribe((state) =\u003e state.paw, console.log)\n// Subscribe also exposes the previous value\nconst unsub3 = useDogStore.subscribe(\n  (state) =\u003e state.paw,\n  (paw, previousPaw) =\u003e console.log(paw, previousPaw)\n)\n// Subscribe also supports an optional equality function\nconst unsub4 = useDogStore.subscribe(\n  (state) =\u003e [state.paw, state.fur],\n  console.log,\n  { equalityFn: shallow }\n)\n// Subscribe and fire immediately\nconst unsub5 = useDogStore.subscribe((state) =\u003e 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(() =\u003e ({ ... }))\nconst { getState, setState, subscribe } = 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) =\u003e 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 =\u003e ({ scratches: 0, ... }))\n\nconst Component = () =\u003e {\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(() =\u003e useScratchStore.subscribe(\n    state =\u003e (scratchRef.current = state.scratches)\n  ), [])\n  ...\n```\n\n## Sick of reducers and changing nested state? 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) =\u003e ({\n  lush: { forest: { contains: { a: 'bear' } } },\n  clearForest: () =\u003e\n    set(\n      produce((state) =\u003e {\n        state.lush.forest.contains = null\n      })\n    ),\n}))\n\nconst clearForest = useLushStore((state) =\u003e state.clearForest)\nclearForest()\n```\n\n[Alternatively, there are some other solutions.](./docs/guides/updating-state.md#with-immer)\n\n## Middleware\n\nYou can functionally compose your store any way you like.\n\n```jsx\n// Log every time state is changed\nconst log = (config) =\u003e (set, get, api) =\u003e\n  config(\n    (...args) =\u003e {\n      console.log('  applying', args)\n      set(...args)\n      console.log('  new state', get())\n    },\n    get,\n    api\n  )\n\nconst useBeeStore = create(\n  log((set) =\u003e ({\n    bees: false,\n    setBees: (input) =\u003e set({ bees: input }),\n  }))\n)\n```\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) =\u003e ({\n      fishes: 0,\n      addAFish: () =\u003e set({ fishes: get().fishes + 1 }),\n    }),\n    {\n      name: 'food-storage', // unique name\n      storage: createJSONStorage(() =\u003e 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) =\u003e ({\n    bees: 0,\n    addBees: (by) =\u003e\n      set((state) =\u003e {\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 }) =\u003e {\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) =\u003e ({\n  grumpiness: 0,\n  dispatch: (args) =\u003e set((state) =\u003e reducer(state, args)),\n}))\n\nconst dispatch = useGrumpyStore((state) =\u003e state.dispatch)\ndispatch({ type: types.increase, by: 2 })\n```\n\nOr, 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.\n\n```jsx\nimport { redux } from 'zustand/middleware'\n\nconst useGrumpyStore = create(redux(reducer, initialState))\n```\n\n## Redux devtools\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(store))\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(store), { name, store: storeName1 })\nconst usePlainStore2 = create(devtools(store), { 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(store, {name: \"MyStore\"})`, which will create a separate instance named \"MyStore\" in the devtools.\n\nSerialize options: `devtools(store, { 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 createBearSlice = (set, get) =\u003e ({\n  eatFish: () =\u003e\n    set(\n      (prev) =\u003e ({ fishes: prev.fishes \u003e 1 ? prev.fishes - 1 : 0 }),\n      false,\n      'bear/eatFish'\n    ),\n})\n```\n\nYou can also log the action's type along with its payload:\n\n```jsx\nconst createBearSlice = (set, get) =\u003e ({\n  addFishes: (count) =\u003e\n    set((prev) =\u003e ({ fishes: prev.fishes + count }), false, {\n      type: 'bear/addFishes',\n      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 = () =\u003e (\n  \u003cStoreContext.Provider value={store}\u003e\n    ...\n  \u003c/StoreContext.Provider\u003e\n)\n\nconst Component = () =\u003e {\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\u003cState\u003e()(...)` instead of `create(...)`...\n\n```ts\nimport { create } from 'zustand'\nimport { devtools, persist } from 'zustand/middleware'\n\ninterface BearState {\n  bears: number\n  increase: (by: number) =\u003e void\n}\n\nconst useBearStore = create\u003cBearState\u003e()(\n  devtools(\n    persist(\n      (set) =\u003e ({\n        bears: 0,\n        increase: (by) =\u003e set((state) =\u003e ({ 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\n## Third-Party Libraries\n\nSome users may want to extends 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 valtio](https://github.com/pmndrs/zustand/wiki/Difference-between-zustand-and-valtio)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbarelyhuman%2Fzustand","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbarelyhuman%2Fzustand","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbarelyhuman%2Fzustand/lists"}