derive-zustand
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

derive-zustand

CI npm size discord

A function to create a derived Zustand store from stores

Install

npm install zustand derive-zustand

Usage

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<number>((get) => get(useCountStore).count * 2);
const useDoubleCountStore = () => useStore(doubleCountStore);

const Counter = () => {
  const { count, inc } = useCountStore();
  const doubleCount = useDoubleCountStore();
  return (
    <div>
      <div>count: {count}</div>
      <div>doubleCount: {doubleCount}</div>
      <button type="button" onClick={inc}>
        +1
      </button>
    </div>
  );
};

Examples

The examples folder contains working examples. You can run one of them with

PORT=8080 pnpm run examples:01_counter

and open http://localhost:8080 in your web browser.

You can also try them directly: 01 02

/derive-zustand/

    Package Sidebar

    Install

    npm i derive-zustand

    Weekly Downloads

    4,004

    Version

    0.1.1

    License

    MIT

    Unpacked Size

    13.3 kB

    Total Files

    9

    Last publish

    Collaborators

    • daishi