{"_id":"@abraaoz/zustand","_rev":"3-1e3fd1d7bfe11b8f4a3d7c3a8e0484a3","name":"@abraaoz/zustand","dist-tags":{"latest":"3.5.13-with-types"},"versions":{"3.5.13":{"name":"@abraaoz/zustand","private":false,"version":"3.5.13","description":"🐻 Bear necessities for state management in React","main":"./index.js","types":"./index.d.ts","exports":{"./package.json":"./package.json",".":{"types":"./index.d.ts","module":"./esm/index.js","import":"./esm/index.mjs","default":"./index.js"},"./vanilla":{"types":"./vanilla.d.ts","module":"./esm/vanilla.js","import":"./esm/vanilla.mjs","default":"./vanilla.js"},"./middleware":{"types":"./middleware.d.ts","module":"./esm/middleware.js","import":"./esm/middleware.mjs","default":"./middleware.js"},"./shallow":{"types":"./shallow.d.ts","module":"./esm/shallow.js","import":"./esm/shallow.mjs","default":"./shallow.js"},"./context":{"types":"./context.d.ts","module":"./esm/context.js","import":"./esm/context.mjs","default":"./context.js"}},"sideEffects":false,"scripts":{"prebuild":"shx rm -rf dist","build":"concurrently 'yarn:build:*'","build:base":"rollup -c","build:vanilla":"rollup -c --config-vanilla","build:middleware":"rollup -c --config-middleware","build:shallow":"rollup -c --config-shallow","build:context":"rollup -c --config-context","postbuild":"yarn copy","eslint":"eslint --fix '*.{js,json}' '{src,tests}/**/*.{ts,tsx}'","eslint:ci":"eslint '*.{js,json}' '{src,tests}/**/*.{ts,tsx}'","pretest":"tsc --noEmit","test":"jest","test:ci":"jest","test:dev":"jest --watch --no-coverage","test:coverage:watch":"jest --watch","copy":"shx cp -r dist/src/* dist/esm && shx mv dist/src/* dist && shx rm -rf dist/{src,tests} && shx cp package.json readme.md LICENSE dist && json -I -f dist/package.json -e \"this.private=false; this.devDependencies=undefined; this.optionalDependencies=undefined; this.scripts=undefined; this.prettier=undefined; this.jest=undefined; this['lint-staged']=undefined;\""},"engines":{"node":">=12.7.0"},"prettier":{"semi":false,"trailingComma":"es5","singleQuote":true,"jsxBracketSameLine":true,"tabWidth":2,"printWidth":80},"lint-staged":{"*.{js,ts,tsx}":["prettier --write"]},"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","jest":{"rootDir":".","testEnvironment":"jsdom","moduleNameMapper":{"^zustand$":"<rootDir>/src/index.ts","^zustand/(.*)$":"<rootDir>/src/$1.ts"},"modulePathIgnorePatterns":["dist"],"testRegex":"test.(js|ts|tsx)$","coverageDirectory":"./coverage/","collectCoverage":true,"coverageReporters":["json","html","text","text-summary"],"collectCoverageFrom":["src/**/*.{js,ts,tsx}","tests/**/*.{js,ts,tsx}"]},"devDependencies":{"@babel/core":"^7.15.8","@babel/plugin-external-helpers":"^7.14.5","@babel/plugin-transform-react-jsx":"^7.14.9","@babel/plugin-transform-runtime":"^7.15.8","@babel/plugin-transform-typescript":"^7.15.8","@babel/preset-env":"^7.15.8","@rollup/plugin-babel":"^5.3.0","@rollup/plugin-node-resolve":"^13.0.5","@rollup/plugin-typescript":"^8.2.5","@testing-library/react":"^12.1.2","@types/jest":"^27.0.2","@types/react":"^17.0.27","@types/react-dom":"^17.0.9","@typescript-eslint/eslint-plugin":"^4.33.0","@typescript-eslint/parser":"^4.33.0","concurrently":"^6.3.0","esbuild":"^0.13.4","eslint":"^7.32.0","eslint-config-prettier":"^8.3.0","eslint-import-resolver-alias":"^1.1.2","eslint-plugin-import":"^2.24.2","eslint-plugin-jest":"^24.5.2","eslint-plugin-prettier":"^4.0.0","eslint-plugin-react":"^7.26.1","eslint-plugin-react-hooks":"^4.2.0","husky":"^7.0.2","immer":"^9.0.6","jest":"^27.2.4","json":"^11.0.0","lint-staged":"^11.2.0","prettier":"^2.4.1","react":"^17.0.2","react-dom":"^17.0.2","rollup":"^2.58.0","rollup-plugin-esbuild":"^4.5.0","shx":"^0.3.3","typescript":"^4.4.3"},"peerDependencies":{"react":">=16.8"},"peerDependenciesMeta":{"react":{"optional":true}},"gitHead":"47668b87b6a0551a7924b9d9e2e4bf9a2a9fdbdf","_id":"@abraaoz/zustand@3.5.13","_nodeVersion":"14.17.0","_npmVersion":"8.0.0","dist":{"integrity":"sha512-qFdCM80Ca99NVZXEq5AB2CHT6RIhPemq6YmQU/IIwmtNt1RzElGEWn3+XT969sTWPllZlevTtq/OBoYwos5coA==","shasum":"39be31fb8478dabd2bb432fdb962256c9f865a0f","tarball":"https://registry.npmjs.org/@abraaoz/zustand/-/zustand-3.5.13.tgz","fileCount":162,"unpackedSize":5740157,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDi7CVJzFQaUWsxu6QIAAlTmiJtVXqekYfkpzIeXF4btAIgMYyTZveh2lM9sdnFyPOiGfbXeqfCwCcIrBctMek0oik="}]},"_npmUser":{"name":"abraaoz","email":"abraao.zaidan@gmail.com"},"directories":{},"maintainers":[{"name":"abraaoz","email":"abraao.zaidan@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/zustand_3.5.13_1634232076548_0.9304984756951902"},"_hasShrinkwrap":false},"3.5.13-with-types":{"name":"@abraaoz/zustand","private":false,"version":"3.5.13-with-types","description":"🐻 Bear necessities for state management in React","main":"./index.js","types":"./index.d.ts","exports":{"./package.json":"./package.json",".":{"types":"./index.d.ts","module":"./esm/index.js","import":"./esm/index.mjs","default":"./index.js"},"./vanilla":{"types":"./vanilla.d.ts","module":"./esm/vanilla.js","import":"./esm/vanilla.mjs","default":"./vanilla.js"},"./middleware":{"types":"./middleware.d.ts","module":"./esm/middleware.js","import":"./esm/middleware.mjs","default":"./middleware.js"},"./shallow":{"types":"./shallow.d.ts","module":"./esm/shallow.js","import":"./esm/shallow.mjs","default":"./shallow.js"},"./context":{"types":"./context.d.ts","module":"./esm/context.js","import":"./esm/context.mjs","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","peerDependencies":{"react":">=16.8"},"peerDependenciesMeta":{"react":{"optional":true}},"gitHead":"609d77f57085855113cb3d2dcaf1d17d41a90699","_id":"@abraaoz/zustand@3.5.13-with-types","_nodeVersion":"14.17.0","_npmVersion":"8.0.0","dist":{"integrity":"sha512-wDsmCtBp6zraCKseO0q58mvuQVxzCpUoulas0qjF1WHWBk8vZAJOBVzP8kb3dG39E7kh4gk8IL48xtpmOWQ3Ng==","shasum":"af44b88e445636dbc4c95e61884d5bb1cd5f18e9","tarball":"https://registry.npmjs.org/@abraaoz/zustand/-/zustand-3.5.13-with-types.tgz","fileCount":28,"unpackedSize":85976,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJhuyFiCRA9TVsSAnZWagAAAZAQAIxPgUxD2YrFRN72NP6I\n62EFM1QIY8AWNBNkqtd6tvx23MibD2OWsomQqY/W0/Gnuu4et/BzR2jLIxT2\nraBRHaB3+c/P1SBD/7nYdrE5yhLhiNqlKpUUFUIvAk0fLYdq6LNu7xPO8Npu\n9T2k2WJ+8SE8OfNLlMpW74ZhbitL7uCFgjob2RUldeHFSSCzpp1KVUurJfdA\nS8tU2WyVO8Egk5K3L8+tRlvwHAwmGJksfEokwMjubElkPJ85tZIgup496nxF\nezXIczgmkXev7vOceP8FxgGd8UYMdQzSYKJyv3s5lmC6jGhBNMQftjffDE1O\n3GuM9pVWyPjMd2XaSZtGAVRhsDswwNpjC7/GRg5itW/NIETm1QILla1pBl7s\n2uscOGZ7w+PvIBAY5G6dWtwZZgE3lYrC1B1GO6Zysp6Pdx3jOjVV8m72KxVW\nh5Sk/cNMI/Pvl52CWp7xqlUTfbt5IUk1RqCuauELezLcqQ3cSg90GbRGelf1\nXGSldYTphBg5y//11DQkPy7in5+0LQkcA5oEATL7N/uzSSDQoA/w/bSDeBO7\n3RgONGspVhPvzuS2czZSh1EpLBPQuyv6AQekxmg7aEW9+/U55ALkdr91i/pv\nR8S5tm9JHJGWNJENiUOgvgpP4LYGk9QgWr2egEBFN9GsSXqtrtTR5iBs06fP\n6+3u\r\n=JfU/\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQC7WjgBvGykvaQwtVaBObpbqZlG5gyyCKjgI8HFCpgbqAIhAP/ROsYOquwfJZWl1n09nVosXd/ZrTFg1CUvryMKfY5a"}]},"_npmUser":{"name":"abraaoz","email":"abraao.zaidan@gmail.com"},"directories":{},"maintainers":[{"name":"abraaoz","email":"abraao.zaidan@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/zustand_3.5.13-with-types_1634234367275_0.3965289063833284"},"_hasShrinkwrap":false}},"time":{"created":"2021-10-14T17:21:16.480Z","3.5.13":"2021-10-14T17:21:17.085Z","modified":"2022-04-04T11:01:36.499Z","3.5.13-with-types":"2021-10-14T17:59:27.452Z"},"maintainers":[{"name":"abraaoz","email":"abraao.zaidan@gmail.com"}],"description":"🐻 Bear necessities for state management in React","homepage":"https://github.com/pmndrs/zustand","keywords":["react","state","manager","management","redux","store"],"repository":{"type":"git","url":"git+https://github.com/pmndrs/zustand.git"},"contributors":[{"name":"Jeremy Holcomb","url":"https://github.com/JeremyRH"},{"name":"Daishi Kato","url":"https://github.com/dai-shi"}],"author":{"name":"Paul Henschel"},"bugs":{"url":"https://github.com/pmndrs/zustand/issues"},"license":"MIT","readme":"<p align=\"center\">\n  <img src=\"bear.jpg\" />\n</p>\n\n[![Build Status](https://img.shields.io/github/workflow/status/pmndrs/zustand/Lint?style=flat&colorA=000000&colorB=000000)](https://github.com/pmndrs/zustand/actions?query=workflow%3ALint)\n[![Build Size](https://img.shields.io/bundlephobia/min/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 to deal 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://codesandbox.io/s/dazzling-moon-itop4).\n\n```bash\nnpm install zustand@npm:@abraaoz/zustand # or yarn add zustand@npm:@abraaoz/zustand\n```\n\n## Fork motivation\n\nThis is a fork of https://github.com/pmndrs/zustand. This fork allows you to import the following TypeScript definitions:\n\n```jsx\nimport {\n  Combine,\n  DeepPartial,\n  StorageValue,\n  PersistOptions,\n} from 'zustand/middleware'\n```\n\nTo publish a new version at npm, run `npm version (x.y.z)-with-types`, `yarn build`, `cd dist` then `npm publish --access public`.\n\n## First create a store\n\nYour store is a hook! You can put anything in it: primitives, objects, functions. The `set` function *merges* state.\n\n```jsx\nimport create from 'zustand'\n\nconst useStore = 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 needed. Select your state and the component will re-render on changes.\n\n```jsx\nfunction BearCounter() {\n  const bears = useStore(state => state.bears)\n  return <h1>{bears} around here ...</h1>\n}\n\nfunction Controls() {\n  const increasePopulation = useStore(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-occuring-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 = useStore()\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 = useStore(state => state.nuts)\nconst honey = useStore(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 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 } = useStore(state => ({ nuts: state.nuts, honey: state.honey }), shallow)\n\n// Array pick, re-renders the component when either state.nuts or state.honey change\nconst [nuts, honey] = useStore(state => [state.nuts, state.honey], shallow)\n\n// Mapped picks, re-renders the component when state.treats changes in order, count or keys\nconst treats = useStore(state => 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 = useStore(\n  state => state.treats,\n  (oldTreats, newTreats) => compare(oldTreats, newTreats)\n)\n```\n\n## Memoizing selectors\n\nIt is generally recommended to memoize selectors with useCallback. This will prevent unnecessary computations each render. It also allows React to optimize performance in concurrent mode.\n\n```jsx\nconst fruit = useStore(useCallback(state => state.fruits[id], [id]))\n```\n\nIf a selector doesn't depend on scope, you can define it outside the render function to obtain a fixed reference without useCallback.\n\n```jsx\nconst selector = state => state.berries\n\nfunction Component() {\n  const berries = useStore(selector)\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 useStore = 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 useStore = 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 useStore = create((set, get) => ({\n  sound: \"grunt\",\n  action: () => {\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 useStore = create(() => ({ paw: true, snout: true, fur: true }))\n\n// Getting non-reactive fresh state\nconst paw = useStore.getState().paw\n// Listening to all changes, fires on every change\nconst unsub1 = useStore.subscribe(console.log)\n// Listening to selected changes, in this case when \"paw\" changes\nconst unsub2 = useStore.subscribe(console.log, state => state.paw)\n// Subscribe also supports an optional equality function\nconst unsub3 = useStore.subscribe(console.log, state => [state.paw, state.fur], shallow)\n// Subscribe also exposes the previous value\nconst unsub4 = useStore.subscribe((paw, previousPaw) => console.log(paw, previousPaw), state => state.paw)\n// Updating state, will trigger listeners\nuseStore.setState({ paw: false })\n// Unsubscribe listeners\nunsub1()\nunsub2()\nunsub3()\nunsub4()\n// Destroying the store (removing all listeners)\nuseStore.destroy()\n\n// You can of course use the hook as you always would\nfunction Component() {\n  const paw = useStore(state => state.paw)\n```\n\n## Using zustand without React\n\nZustands 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 create from 'zustand/vanilla'\n\nconst store = create(() => ({ ... }))\nconst { getState, setState, subscribe, destroy } = store\n```\n\nYou can even consume an existing vanilla store with React:\n\n```jsx\nimport create from 'zustand'\nimport vanillaStore from './vanillaStore'\n\nconst useStore = create(vanillaStore)\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 occuring 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 useStore = create(set => ({ scratches: 0, ... }))\n\nfunction Component() {\n  // Fetch initial state\n  const scratchRef = useRef(useStore.getState().scratches)\n  // Connect to the store on mount, disconnect on unmount, catch state-changes in a reference\n  useEffect(() => useStore.subscribe(\n    scratches => (scratchRef.current = scratches),\n    state => state.scratches\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 useStore = create(set => ({\n  lush: { forest: { contains: { a: \"bear\" } } },\n  clearForest: () => set(produce(state => {\n    state.lush.forest.contains = null\n  }))\n}))\n\nconst clearForest = useStore(state => state.clearForest)\nclearForest();\n```\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 => (set, get, api) => config(args => {\n  console.log(\"  applying\", args)\n  set(args)\n  console.log(\"  new state\", get())\n}, get, api)\n\n// Turn the set method into an immer proxy\nconst immer = config => (set, get, api) => config((partial, replace) => {\n  const nextState = typeof partial === 'function'\n      ? produce(partial)\n      : partial\n  return set(nextState, replace)\n}, get, api)\n\nconst useStore = create(\n  log(\n    immer((set) => ({\n      bees: false,\n      setBees: (input) => set((state) => void (state.bees = input)),\n    })),\n  ),\n)\n```\n\n<details>\n<summary>How to pipe middlewares</summary>\n\n```js\nimport create from \"zustand\"\nimport produce from \"immer\"\nimport pipe from \"ramda/es/pipe\"\n\n/* log and immer functions from previous example */\n/* you can pipe as many middlewares as you want */\nconst createStore = pipe(log, immer, create)\n\nconst useStore = createStore(set => ({\n  bears: 1,\n  increasePopulation: () => set(state => ({ bears: state.bears + 1 }))\n}))\n\nexport default useStore\n```\nFor a TS example see the following [discussion](https://github.com/pmndrs/zustand/discussions/224#discussioncomment-118208)\n</details>\n\n<details>\n<summary>How to type immer middleware in TypeScript</summary>\n\n```ts\nimport { State, StateCreator } from 'zustand'\nimport produce, { Draft } from 'immer'\n\nconst immer = <T extends State>(config: StateCreator<T>): StateCreator<T> => \n  (set, get, api) => config((partial, replace) => {\n    const nextState =\n      typeof partial === 'function'\n        ? produce(partial as (state: Draft<T>) => T)\n        : partial as T\n    return set(nextState, replace)\n  }, get, api)\n```\n\n</details>\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 } from \"zustand/middleware\"\n\nexport const useStore = create(persist(\n  (set, get) => ({\n    fishes: 0,\n    addAFish: () => set({ fishes: get().fishes + 1 })\n  }),\n  {\n    name: \"food-storage\", // unique name\n    getStorage: () => sessionStorage, // (optional) by default the 'localStorage' is used\n  }\n))\n```\n\n<details>\n<summary>How to use custom storage engines</summary>\n\nYou can use other storage methods outside of `localStorage` and `sessionStorage` by defining your own `StateStorage`. A custom `StateStorage` object also allows you to write middlware for the persisted store when getting or setting store data.\n\n```tsx\nimport create from \"zustand\"\nimport { persist, StateStorage } from \"zustand/middleware\"\nimport { get, set } from 'idb-keyval' // can use anything: IndexedDB, Ionic Storage, etc.\n\n// Custom storage object\nconst storage: StateStorage = {\n  getItem: async (name: string): Promise<string | null> => {\n    console.log(name, \"has been retrieved\");\n    return await get(name) || null\n  },\n  setItem: async (name: string, value: string): Promise<void> => {\n    console.log(name, \"with value\", value, \"has been saved\");\n    set(name, value)\n  }\n}\n\nexport const useStore = create(persist(\n  (set, get) => ({\n    fishes: 0,\n    addAFish: () => set({ fishes: get().fishes + 1 })\n  }),\n  {\n    name: \"food-storage\", // unique name\n    getStorage: () => storage,\n  }\n))\n```\n\n</details>\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: return { grumpiness: state.grumpiness + by }\n    case types.decrease: return { grumpiness: state.grumpiness - by }\n  }\n}\n\nconst useStore = create(set => ({\n  grumpiness: 0,\n  dispatch: args => set(state => reducer(state, args)),\n}))\n\nconst dispatch = useStore(state => 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. Try [this](https://codesandbox.io/s/amazing-kepler-swxol) example.\n\n```jsx\nimport { redux } from 'zustand/middleware'\n\nconst useStore = create(redux(reducer, initialState))\n```\n\n## Calling actions outside a React event handler\n\nBecause React handles `setState` synchronously if it's called outside an event handler. Updating the state outside an event handler will force react to update the components synchronously, therefore adding the risk of encountering the zombie-child effect.\nIn order to fix this, the action needs to be wrapped in `unstable_batchedUpdates`\n\n```jsx\nimport { unstable_batchedUpdates } from 'react-dom' // or 'react-native'\n\nconst useStore = create((set) => ({\n  fishes: 0,\n  increaseFishes: () => set((prev) => ({ fishes: prev.fishes + 1 }))\n}))\n\nconst nonReactCallback = () => {\n  unstable_batchedUpdates(() => {\n    useStore.getState().increaseFishes()\n  })\n}\n```\n\nMore details: https://github.com/pmndrs/zustand/issues/302\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 useStore = create(devtools(store))\n// Usage with a redux store, it will log full action types\nconst useStore = create(devtools(redux(reducer, initialState)))\n```\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 be prefixed to your actions.  \nSerialize options: `devtools(store, { serialize: { options: true } })`.  \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\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 store is a hook, passing it as a normal context value may violate rules of hooks. To avoid misusage, a special `createContext` is provided.\n\n```jsx\nimport create from 'zustand'\nimport createContext from 'zustand/context'\n\nconst { Provider, useStore } = createContext()\n\nconst createStore = () => create(...)\n\nconst App = () => (\n  <Provider createStore={createStore}>\n    ...\n  </Provider>\n)\n\nconst Component = () => {\n  const state = useStore()\n  const slice = useStore(selector)\n  ...\n}\n```\n<details>\n  <summary>createContext usage in real components</summary>\n\n  ```jsx\n  import create from \"zustand\";\n  import createContext from \"zustand/context\";\n\n  // Best practice: You can move the below createContext() and createStore to a separate file(store.js) and import the Provider, useStore here/wherever you need.\n\n  const { Provider, useStore } = createContext();\n\n  const createStore = () =>\n    create((set) => ({\n      bears: 0,\n      increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),\n      removeAllBears: () => set({ bears: 0 })\n    }));\n\n  const Button = () => {\n    return (\n        {/** store() - This will create a store for each time using the Button component instead of using one store for all components **/}\n      <Provider createStore={createStore}> \n        <ButtonChild />\n      </Provider>\n    );\n  };\n\n  const ButtonChild = () => {\n    const state = useStore();\n    return (\n      <div>\n        {state.bears}\n        <button\n          onClick={() => {\n            state.increasePopulation();\n          }}\n        >\n          +\n        </button>\n      </div>\n    );\n  };\n\n  export default function App() {\n    return (\n      <div className=\"App\">\n        <Button />\n        <Button />\n      </div>\n    );\n  }\n  ```\n</details>\n\n<details>\n  <summary>createContext usage with initialization from props (in TypeScript)</summary>\n\n  ```tsx\n  import create from \"zustand\";\n  import createContext from \"zustand/context\";\n\n  type BearState = {\n    bears: number\n    increase: () => void\n  }\n\n  // pass the type to `createContext` rather than to `create`\n  const { Provider, useStore } = createContext<BearState>();\n\n  export default function App({ initialBears }: { initialBears: number }) {\n    return (\n      <Provider\n        createStore={() =>\n          create((set) => ({\n            bears: initialBears,\n            increase: () => set((state) => ({ bears: state.bears + 1 })),\n          }))\n        }\n      >\n        <Button />\n      </Provider>\n  )\n}\n  ```\n</details>\n\n## Typing your store and `combine` middleware\n\n```tsx\n// You can use `type`\ntype BearState = {\n  bears: number\n  increase: (by: number) => void\n}\n\n// Or `interface`\ninterface BearState {\n  bears: number\n  increase: (by: number) => void\n}\n\n// And it is going to work for both\nconst useStore = create<BearState>(set => ({\n  bears: 0,\n  increase: (by) => set(state => ({ bears: state.bears + by })),\n}))\n```\n\nOr, use `combine` and let tsc infer types. This merges two states shallowly.\n\n```tsx\nimport { combine } from 'zustand/middleware'\n\nconst useStore = create(\n  combine(\n    { bears: 0 },\n    (set) => ({ increase: (by: number) => set((state) => ({ bears: state.bears + by })) })\n  ),\n)\n```\n  \n## Best practices\n  \n* You may wonder how to organize your code for better maintenance: [Splitting the store into seperate slices](https://github.com/pmndrs/zustand/wiki/Splitting-the-store-into-separate-slices).\n  \n* Recommended usage for this unopinionated library: [Flux inspired practice](https://github.com/pmndrs/zustand/wiki/Flux-inspired-practice).\n  \n## Testing\n\nFor information regarding testing with Zustand, visit the dedicated [Wiki page](https://github.com/pmndrs/zustand/wiki/Testing).\n\n## 3rd-Party Libraries\n\nSome users may want to extends Zustand's feature set which can be done using 3rd-party libraries made by the community. For information regarding 3rd-party libraries with Zustand, visit the dedicated [Wiki page](https://github.com/pmndrs/zustand/wiki/3rd-Party-Libraries).\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","readmeFilename":"readme.md"}