{"id":13401043,"url":"https://github.com/pmndrs/zustand","last_synced_at":"2025-12-15T16:01:03.359Z","repository":{"id":37036392,"uuid":"180328715","full_name":"pmndrs/zustand","owner":"pmndrs","description":"🐻 Bear necessities for state management in React","archived":false,"fork":false,"pushed_at":"2025-12-11T11:45:18.000Z","size":7876,"stargazers_count":56088,"open_issues_count":3,"forks_count":1889,"subscribers_count":180,"default_branch":"main","last_synced_at":"2025-12-11T15:43:43.917Z","etag":null,"topics":["hacktoberfest","hooks","react","react-context","reactjs","redux","state-management"],"latest_commit_sha":null,"homepage":"https://zustand-demo.pmnd.rs/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pmndrs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":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","https://daishi.gumroad.com/l/learn-zustand-v4"]}},"created_at":"2019-04-09T09:10:06.000Z","updated_at":"2025-12-11T14:40:39.000Z","dependencies_parsed_at":"2024-03-12T15:25:59.482Z","dependency_job_id":"04517ff8-b2d3-47ff-97ae-47953da41275","html_url":"https://github.com/pmndrs/zustand","commit_stats":{"total_commits":1063,"total_committers":266,"mean_commits":"3.9962406015037595","dds":0.8118532455315146,"last_synced_commit":"c87a5d69ad2662be99a5caa34ba1b9027b6842a4"},"previous_names":["drcmda/msga","react-spring/zustand","drcmda/zustand"],"tags_count":131,"template":false,"template_full_name":null,"purl":"pkg:github/pmndrs/zustand","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pmndrs%2Fzustand","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pmndrs%2Fzustand/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pmndrs%2Fzustand/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pmndrs%2Fzustand/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pmndrs","download_url":"https://codeload.github.com/pmndrs/zustand/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pmndrs%2Fzustand/sbom","scorecard":{"id":355370,"data":{"date":"2025-08-11","repo":{"name":"github.com/pmndrs/zustand","commit":"f831bc8d71f3a23f4f0bc65462ca852792566cfc"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":5.7,"checks":[{"name":"Code-Review","score":6,"reason":"Found 18/30 approved changesets -- score normalized to 6","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Maintained","score":10,"reason":"30 commit(s) and 4 issue activity found in the last 90 days -- score normalized to 10","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Token-Permissions","score":0,"reason":"detected GitHub workflow tokens with excessive permissions","details":["Warn: no topLevel permission defined: .github/workflows/compressed-size.yml:1","Warn: no topLevel permission defined: .github/workflows/docs.yml:1","Warn: no topLevel permission defined: .github/workflows/preview-release.yml:1","Warn: no topLevel permission defined: .github/workflows/publish.yml:1","Warn: no topLevel permission defined: .github/workflows/test-multiple-builds.yml:1","Warn: no topLevel permission defined: .github/workflows/test-multiple-versions.yml:1","Warn: no topLevel permission defined: .github/workflows/test-old-typescript.yml:1","Warn: no topLevel permission defined: .github/workflows/test.yml:1","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Pinned-Dependencies","score":0,"reason":"dependency not pinned by hash detected -- score normalized to 0","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/compressed-size.yml:9: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/compressed-size.yml/main?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/compressed-size.yml:10: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/compressed-size.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/compressed-size.yml:11: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/compressed-size.yml/main?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/compressed-size.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/compressed-size.yml/main?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/docs.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/docs.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/docs.yml:40: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/docs.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/preview-release.yml:9: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/preview-release.yml/main?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/preview-release.yml:10: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/preview-release.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/preview-release.yml:11: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/preview-release.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish.yml:11: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/publish.yml/main?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/publish.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/publish.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish.yml:13: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/publish.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test-multiple-builds.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/test-multiple-builds.yml/main?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/test-multiple-builds.yml:19: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/test-multiple-builds.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test-multiple-builds.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/test-multiple-builds.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test-multiple-versions.yml:25: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/test-multiple-versions.yml/main?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/test-multiple-versions.yml:26: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/test-multiple-versions.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test-multiple-versions.yml:27: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/test-multiple-versions.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test-old-typescript.yml:31: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/test-old-typescript.yml/main?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/test-old-typescript.yml:32: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/test-old-typescript.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test-old-typescript.yml:33: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/test-old-typescript.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:13: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/test.yml/main?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/test.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/test.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/pmndrs/zustand/test.yml/main?enable=pin","Info:   0 out of  15 GitHub-owned GitHubAction dependencies pinned","Info:   0 out of   9 third-party GitHubAction dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Info: FSF or OSI recognized license: MIT License: LICENSE:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Branch-Protection","score":-1,"reason":"internal error: error during branchesHandler.setup: internal error: githubv4.Query: Resource not accessible by integration","details":null,"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"Packaging","score":10,"reason":"packaging workflow detected","details":["Info: Project packages its releases by way of GitHub Actions.: .github/workflows/publish.yml:8"],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 27 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}},{"name":"Vulnerabilities","score":10,"reason":"0 existing vulnerabilities detected","details":null,"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}}]},"last_synced_at":"2025-08-18T09:25:00.210Z","repository_id":37036392,"created_at":"2025-08-18T09:25:00.210Z","updated_at":"2025-08-18T09:25:00.210Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":27676003,"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","status":"online","status_checked_at":"2025-12-12T02:00:06.775Z","response_time":129,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["hacktoberfest","hooks","react","react-context","reactjs","redux","state-management"],"created_at":"2024-07-30T19:00:58.139Z","updated_at":"2025-12-15T16:01:03.352Z","avatar_url":"https://github.com/pmndrs.png","language":"TypeScript","funding_links":["https://github.com/sponsors/dai-shi","https://daishi.gumroad.com/l/uaxms","https://daishi.gumroad.com/l/learn-zustand-v4"],"categories":["Core","TypeScript","Uncategorized","四、状态管理与数据获取","State Management","Технологии","Utilities","Frontend React","🐉 The technologies being used","Frontend","Tools","React","Explanation of each State Management","Other Notable Libraries","数据流","React 相关","语言资源库","前端开发框架及项目","目录","Get Involved","State management:","redux","🛠️ Technologies Used","React [🔝](#readme)","⚛️ React Native Architecture","State management","⚛️ React Libraries","📖 Categories","State Managers","Web Frontend","🌐 Web Development - Frontend"],"sub_categories":["Uncategorized","1. 状态管理（同步状态）","State Management","State management","Client-State management","Visual Editor","Zustand","macros","typescript","其他_文本生成、文本对话","Structure","🔍 **Quick Access**","Graphics \u0026 Drawing","macOS","React \u0026 UI Libraries"],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg src=\"docs/bear.jpg\" /\u003e\n\u003c/p\u003e\n\n[![Build Status](https://img.shields.io/github/actions/workflow/status/pmndrs/zustand/test.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/badge/dynamic/json?url=https%3A%2F%2Fdeno.bundlejs.com%2F%3Fq%3Dzustand\u0026query=%24.size.uncompressedSize\u0026style=flat\u0026label=bundle%20size\u0026colorA=000000\u0026colorB=000000)](https://bundlejs.com/?q=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\n\u003ca href=\"https://dai-shi.github.io/zustand-banner-sponsorship/sponsors/\" target=\"_blank\" rel=\"noopener\"\u003e\n  \u003cp align=\"center\"\u003e\n    \u003cimg src=\"https://dai-shi.github.io/zustand-banner-sponsorship/api/banner.png\" /\u003e\n  \u003c/p\u003e\n\u003c/a\u003e\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](https://zustand-demo.pmnd.rs/) and read the [docs](https://zustand.docs.pmnd.rs/).\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](./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 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) =\u003e ({\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) =\u003e ({ 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) =\u003e [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) =\u003e 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) =\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\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(({ tuna, ...rest }) =\u003e 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) =\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## 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(() =\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\nfunction Component() {\n  const paw = useDogStore((state) =\u003e 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(() =\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((set) =\u003e ...)\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) =\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 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) =\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## 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', // name of the item in the storage (must be unique)\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 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) =\u003e ...))\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) =\u003e ..., { name, store: storeName1 }))\nconst usePlainStore2 = create(devtools((set) =\u003e ..., { name, store: storeName2 }))\n// 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://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) =\u003e ({\n  ...\n  eatFish: () =\u003e set(\n    (prev) =\u003e ({ fishes: prev.fishes \u003e 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) =\u003e set(\n    (prev) =\u003e ({ 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 = () =\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'\nimport type {} from '@redux-devtools/extension' // required for devtools typing\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 detailed TypeScript guide is [here](docs/guides/beginner-typescript.md) and [there](docs/guides/advanced-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://zustand.docs.pmnd.rs/getting-started/comparison)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpmndrs%2Fzustand","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpmndrs%2Fzustand","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpmndrs%2Fzustand/lists"}