Skip to content

zustandjs/zustand-xs

Repository files navigation

zustand-xs

CI npm size discord

XState/store compabile middleware for Zustand

Motivation

Just for fun. Inspired by https://tkdodo.eu/blog/introducing-x-state-store.

Install

npm install zustand zustand-xs

Usage

import { create } from 'zustand';
import { xs } from 'zustand-xs';

const useCountStore = create(
  xs(
    {
      count: 0,
      text: 'hello',
    },
    {
      inc: {
        count: (context) => context.count + 1,
      },
      updateText: (_context, event: { text: string }) => ({
        text: event.text,
      }),
      reset: { count: 0, text: 'hello' },
    },
  ),
);

const Counter = () => {
  const count = useCountStore((state) => state.count);
  const text = useCountStore((state) => state.text);
  const inc = () => useCountStore.send({ type: 'inc' });
  const updateText = (text: string) =>
    useCountStore.send({ type: 'updateText', text });
  const reset = () => useCountStore.send({ type: 'reset' });
  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 pnpm run examples:01_counter

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

You can also try them directly: 01

Tweets

About

XState/store compabile middleware for Zustand

Resources

License

Stars

Watchers

Forks

Packages

No packages published