auto-zustand-selectors-hook

Stop writing selectors and do more work!

Features

  • auto generate selectors for Zustand store
  • 2 styles available
  • Typescript auto completion supported

Install

npm install --save auto-zustand-selectors-hook

Or with yarn:

yarn add auto-zustand-selectors-hook

Usage

Let's say you have a store like this

interface BearState {
  bears: number;
  increase: (by: number) => void;
}

const useStoreBase = create<BearState>((set) => ({
  bears: 0,
  increase: (by) => set((state) => ({ bears: state.bears + by })),
}));

There are two types of selectors you can generate, purely function signature difference, underneath, they are all selectors.

For function style ( createSelectorFunctions )

import { createSelectorFunctions } from 'auto-zustand-selectors-hook';
import { create } from 'zustand';

// wrap your store
const useStore = createSelectorFunctions(useStoreBase);

// use it like this!
// .use.blahblah is a pre-generated selector, yeah!
const TestComponent = () => {
  const bears = useStore.use.bears();
  const increase = useStore.use.increase();

  return (
    <>
      <span>{bears}</span>
      <button
        onClick={() => {
          increase(1);
        }}
      >
        +
      </button>
    </>
  );
};

For hook style ( createSelectorHooks )

import { createSelectorHooks } from 'auto-zustand-selectors-hook';
import { create } from 'zustand';

// create your store
const useStoreBase = create<BearState>((set) => ({
  bears: 0,
  increase: (by) => set((state) => ({ bears: state.bears + by })),
}));

// wrap your store
const useStore = createSelectorHooks(useStoreBase);

// use it like this!
// .useBlahblah is a pre-generated selector, yeah!
const TestComponent = () => {
  const bears = useStore.useBears();
  const increase = useStore.useIncrease();

  return (
    <>
      <span>{bears}</span>
      <button
        onClick={() => {
          increase(1);
        }}
      >
        +
      </button>
    </>
  );
};

License

MIT © Albert Gao

Credits

It all starts from my feature request Thanks dai-shi for the initial implementation and ideas of API.