0.2.0 • Published 15 days ago

zustand-slices v0.2.0

Weekly downloads
-
License
MIT
Repository
github
Last release
15 days ago

zustand-slices

CI npm size discord

A slice utility for Zustand

Install

npm install zustand zustand-slices

Usage

import { create } from 'zustand';
import { createSlice, withSlices } from 'zustand-slices';

const countSlice = createSlice({
  name: 'count',
  value: 0,
  actions: {
    inc: () => (prev) => prev + 1,
    reset: () => () => 0,
  },
});

const textSlice = createSlice({
  name: 'text',
  value: 'Hello',
  actions: {
    updateText: (newText: string) => () => newText,
    reset: () => () => 'Hello',
  },
});

const useCountStore = create(withSlices(countSlice, textSlice));

const Counter = () => {
  const count = useCountStore((state) => state.count);
  const text = useCountStore((state) => state.text);
  const { inc, updateText, reset } = useCountStore.getState();
  return (
    <>
      <p>
        Count: {count}
        <button type="button" onClick={inc}>
          +1
        </button>
      </p>
      <p>
        <input value={text} onChange={(e) => updateText(e.target.value)} />
      </p>
      <p>
        <button type="button" onClick={reset}>
          Reset
        </button>
      </p>
    </>
  );
};

Examples

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

PORT=8080 yarn run examples:01_counter

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

You can also try them in codesandbox.io: 01 02

Tweets

0.2.0

15 days ago

0.1.0

27 days ago

0.0.2

30 days ago

0.0.1

1 month ago

0.0.0

1 month ago