Skip to content

zustandjs/zustand-valtio

Repository files navigation

zustand-valtio

CI npm size discord

A sweet combination of Zustand and Valtio

Install

npm install zustand zustand-valtio valtio

Usage

import { create } from 'zustand';
import { withProxy } from 'zustand-valtio';

const useCounterState = create(
  withProxy({
    count: 0,
    inc() {
      this.count++;
    },
  }),
);

const Counter = () => {
  const count = useCounterState((state) => state.count);
  const inc = useCounterState((state) => state.inc);
  // Or this works too
  // const inc = () => ++useCounterState.getProxyState().count;
  return (
    <>
      <div>Count: {count}</div>
      <button type="button" onClick={inc}>
        +1
      </button>
    </>
  );
};

But, why?

Zustand has immer middleware to update state mutably. Valtio has the same capability. Isn't the combination sweet?

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 03 04

Tweets