[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-557":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":17,"stars7d":18,"stars30d":19,"stars90d":16,"forks30d":16,"starsTrendScore":20,"compositeScore":21,"rankGlobal":10,"rankLanguage":10,"license":22,"archived":23,"fork":23,"defaultBranch":24,"hasWiki":25,"hasPages":25,"topics":26,"createdAt":10,"pushedAt":10,"updatedAt":34,"readmeContent":35,"aiSummary":36,"trendingCount":16,"starSnapshotCount":16,"syncStatus":15,"lastSyncTime":37,"discoverSource":38},557,"zustand","pmndrs\u002Fzustand","pmndrs","🐻 Bear necessities for state management in React","https:\u002F\u002Fzustand-demo.pmnd.rs\u002F",null,"TypeScript",58256,2064,205,2,0,3,88,266,19,44.94,"MIT License",false,"main",true,[27,28,29,30,31,32,33],"hacktoberfest","hooks","react","react-context","reactjs","redux","state-management","2026-06-12 02:00:15","\u003Cp align=\"center\">\n  \u003Cimg src=\".\u002Fdocs\u002Fbear.jpg\" \u002F>\n\u003C\u002Fp>\n\n[![Build Status](https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Factions\u002Fworkflow\u002Fstatus\u002Fpmndrs\u002Fzustand\u002Ftest.yml?branch=main&style=flat&colorA=000000&colorB=000000)](https:\u002F\u002Fgithub.com\u002Fpmndrs\u002Fzustand\u002Factions?query=workflow%3ATest)\n[![Build Size](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fdynamic\u002Fjson?url=https%3A%2F%2Fdeno.bundlejs.com%2F%3Fq%3Dzustand&query=%24.size.uncompressedSize&style=flat&label=bundle%20size&colorA=000000&colorB=000000)](https:\u002F\u002Fbundlejs.com\u002F?q=zustand)\n[![Version](https:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fv\u002Fzustand?style=flat&colorA=000000&colorB=000000)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fzustand)\n[![Downloads](https:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fdt\u002Fzustand.svg?style=flat&colorA=000000&colorB=000000)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fzustand)\n[![Discord Shield](https:\u002F\u002Fimg.shields.io\u002Fdiscord\u002F740090768164651008?style=flat&colorA=000000&colorB=000000&label=discord&logo=discord&logoColor=ffffff)](https:\u002F\u002Fdiscord.gg\u002Fpoimandres)\n\n\u003Ca href=\"https:\u002F\u002Fdai-shi.github.io\u002Fzustand-banner-sponsorship\u002Fsponsors\u002F\" target=\"_blank\" rel=\"noopener\">\n  \u003Cp align=\"center\">\n    \u003Cimg src=\"https:\u002F\u002Fdai-shi.github.io\u002Fzustand-banner-sponsorship\u002Fapi\u002Fbanner.png\" \u002F>\n  \u003C\u002Fp>\n\u003C\u002Fa>\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:\u002F\u002Freact-redux.js.org\u002Fapi\u002Fhooks#stale-props-and-zombie-children), [react concurrency](https:\u002F\u002Fgithub.com\u002Fbvaughn\u002Frfcs\u002Fblob\u002FuseMutableSource\u002Ftext\u002F0000-use-mutable-source.md), and [context loss](https:\u002F\u002Fgithub.com\u002Ffacebook\u002Freact\u002Fissues\u002F13332) 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](https:\u002F\u002Fzustand-demo.pmnd.rs\u002F) and read the [docs](https:\u002F\u002Fzustand.docs.pmnd.rs\u002F).\n\n```bash\nnpm install 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](.\u002Fdocs\u002Fguides\u002Fimmutable-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 \u003Ch1>{bears} around here ...\u003C\u002Fh1>\n}\n\nfunction Controls() {\n  const increasePopulation = useBearStore((state) => state.increasePopulation)\n  return \u003Cbutton onClick={increasePopulation}>one up\u003C\u002Fbutton>\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](.\u002Fdocs\u002Fguides\u002Fprevent-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\u002Freact\u002Fshallow'\n\nconst useBearStore = create((set) => ({\n  nuts: 0,\n  honey: 0,\n  treats: {},\n  \u002F\u002F ...\n}))\n\n\u002F\u002F 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\u002F\u002F 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\u002F\u002F 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`](.\u002Fdocs\u002Fmigrations\u002Fmigrating-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\nconst useFishStore = create((set) => ({\n  salmon: 1,\n  tuna: 2,\n  deleteEverything: () => set({}, true), \u002F\u002F clears the entire store, actions included\n  deleteTuna: () => set(({ tuna, ...rest }) => rest, 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\u002Fwriting 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:\u002F\u002Fgithub.com\u002Freactjs\u002Frfcs\u002Fblob\u002Fmain\u002Ftext\u002F0188-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:\u002F\u002Fgithub.com\u002Fpmndrs\u002Fzustand\u002Fdiscussions\u002F2200).\n\n```jsx\nconst useDogStore = create(() => ({ paw: true, snout: true, fur: true }))\n\n\u002F\u002F Getting non-reactive fresh state\nconst paw = useDogStore.getState().paw\n\u002F\u002F Listening to all changes, fires synchronously on every change\nconst unsub1 = useDogStore.subscribe(console.log)\n\u002F\u002F Updating state, will trigger listeners\nuseDogStore.setState({ paw: false })\n\u002F\u002F Unsubscribe listeners\nunsub1()\n\n\u002F\u002F 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\u002Fmiddleware'\nconst useDogStore = create(\n  subscribeWithSelector(() => ({ paw: true, snout: true, fur: true })),\n)\n\n\u002F\u002F Listening to selected changes, in this case when \"paw\" changes\nconst unsub2 = useDogStore.subscribe((state) => state.paw, console.log)\n\u002F\u002F Subscribe also exposes the previous value\nconst unsub3 = useDogStore.subscribe(\n  (state) => state.paw,\n  (paw, previousPaw) => console.log(paw, previousPaw),\n)\n\u002F\u002F 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\u002F\u002F 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\u002Fvanilla'\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 '.\u002FvanillaStore'\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:\u002F\u002Fcodesandbox.io\u002Fs\u002Fpeaceful-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  \u002F\u002F Fetch initial state\n  const scratchRef = useRef(useScratchStore.getState().scratches)\n  \u002F\u002F 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:\u002F\u002Fgithub.com\u002Fmweststrate\u002Fimmer)?\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.](.\u002Fdocs\u002Fguides\u002Fupdating-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\u002Fmiddleware'\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', \u002F\u002F name of the item in the storage (must be unique)\n      storage: createJSONStorage(() => sessionStorage), \u002F\u002F (optional) by default, 'localStorage' is used\n    },\n  ),\n)\n```\n\n[See the full documentation for this middleware.](.\u002Fdocs\u002Freference\u002Fintegrations\u002Fpersisting-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\u002Fmiddleware\u002Fimmer'\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\u002Fmiddleware'\n\nconst useGrumpyStore = create(redux(reducer, initialState))\n```\n\n## Redux devtools\n\nInstall the [Redux DevTools Chrome extension](https:\u002F\u002Fchromewebstore.google.com\u002Fdetail\u002Fredux-devtools\u002Flmhkpmbekcpmknklioeibfkpmmfibljd) to use the devtools middleware.\n\n```jsx\nimport { devtools } from 'zustand\u002Fmiddleware'\n\n\u002F\u002F Usage with a plain action store, it will log actions as \"setState\"\nconst usePlainStore = create(devtools((set) => ...))\n\u002F\u002F 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\u002Fmiddleware'\n\n\u002F\u002F 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\u002F\u002F Usage with a redux store, it will log full action types\nconst useReduxStore1 = create(devtools(redux(reducer, initialState)), { name, store: storeName3 })\nconst useReduxStore2 = 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:\u002F\u002Fgithub.com\u002Fzalmoxisus\u002Fredux-devtools-extension\u002Fblob\u002Fmaster\u002Fdocs\u002FAPI\u002FArguments.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:\u002F\u002Fgithub.com\u002Fpmndrs\u002Fzustand\u002Fissues\u002F163\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\u002FeatFish'\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\u002FaddFishes', 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(...) \u002F\u002F vanilla store without hooks\n\nconst StoreContext = createContext()\n\nconst App = () => (\n  \u003CStoreContext.Provider value={store}>\n    ...\n  \u003C\u002FStoreContext.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\u003CState>()(...)` instead of `create(...)`...\n\n```ts\nimport { create } from 'zustand'\nimport { devtools, persist } from 'zustand\u002Fmiddleware'\nimport type {} from '@redux-devtools\u002Fextension' \u002F\u002F required for devtools typing\n\ninterface BearState {\n  bears: number\n  increase: (by: number) => void\n}\n\nconst useBearStore = create\u003CBearState>()(\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 detailed TypeScript guide is [here](docs\u002Flearn\u002Fguides\u002Fbeginner-typescript.md) and [there](docs\u002Flearn\u002Fguides\u002Fadvanced-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](.\u002Fdocs\u002Flearn\u002Fguides\u002Fslices-pattern.md).\n- Recommended usage for this unopinionated library: [Flux inspired practice](.\u002Fdocs\u002Flearn\u002Fguides\u002Fflux-inspired-practice.md).\n- [Calling actions outside a React event handler in pre-React 18](.\u002Fdocs\u002Flearn\u002Fguides\u002Fevent-handler-in-pre-react-18.md).\n- [Testing](.\u002Fdocs\u002Flearn\u002Fguides\u002Ftesting.md)\n- For more, have a look [in the docs folder](.\u002Fdocs\u002Findex.md)\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](.\u002Fdocs\u002Freference\u002Fintegrations\u002Fthird-party-libraries.md).\n\n## Comparison with other libraries\n\n- [Difference between zustand and other state management libraries for React](https:\u002F\u002Fzustand.docs.pmnd.rs\u002Flearn\u002Fgetting-started\u002Fcomparison)\n","zustand 是一个轻量、快速且可扩展的状态管理库，专为 React 应用设计。它基于简化版的 Flux 原理，提供了一个简洁易用的 API，主要通过 Hooks 来操作状态，避免了冗余代码和过度设计的问题。zustand 有效解决了僵尸子组件、React 并发模式下的数据同步以及不同渲染器间上下文丢失等常见问题。适用于需要高效状态管理而不希望引入复杂配置的小到中型 React 项目，特别是那些追求开发效率与性能平衡的应用场景。","2026-06-11 02:37:29","top_all"]