https://github.com/zustandjs/derive-zustand
A function to create a derived Zustand store from stores
https://github.com/zustandjs/derive-zustand
Last synced: about 1 year ago
JSON representation
A function to create a derived Zustand store from stores
- Host: GitHub
- URL: https://github.com/zustandjs/derive-zustand
- Owner: zustandjs
- License: mit
- Created: 2022-11-06T15:08:07.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2024-07-04T00:27:20.000Z (almost 2 years ago)
- Last Synced: 2024-10-30T06:22:15.528Z (over 1 year ago)
- Language: TypeScript
- Size: 204 KB
- Stars: 106
- Watchers: 2
- Forks: 0
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# derive-zustand
[](https://github.com/dai-shi/derive-zustand/actions?query=workflow%3ACI)
[](https://www.npmjs.com/package/derive-zustand)
[](https://bundlephobia.com/result?p=derive-zustand)
[](https://discord.gg/MrQdmzd)
A function to create a derived [Zustand](https://github.com/pmndrs/zustand) store from stores
## Install
```bash
npm install zustand derive-zustand
```
## Usage
```tsx
import { create, useStore } from 'zustand';
import { derive } from 'derive-zustand';
const useCountStore = create<{ count: number; inc: () => void }>((set) => ({
count: 0,
inc: () => set((state) => ({ count: state.count + 1 })),
}));
const doubleCountStore = derive((get) => get(useCountStore).count * 2);
const useDoubleCountStore = () => useStore(doubleCountStore);
const Counter = () => {
const { count, inc } = useCountStore();
const doubleCount = useDoubleCountStore();
return (
count: {count}
doubleCount: {doubleCount}
+1
);
};
```
## Examples
The [examples](examples) folder contains working examples.
You can run one of them with
```bash
PORT=8080 pnpm run examples:01_counter
```
and open in your web browser.
You can also try them directly:
[01](https://stackblitz.com/github/zustandjs/derive-zustand/tree/main/examples/01_counter)
[02](https://stackblitz.com/github/zustandjs/derive-zustand/tree/main/examples/02_animals)