0.4.0 • Published 1 year ago
zustand-valtio v0.4.0
zustand-valtio
A sweet combination of Zustand and Valtio
Install
npm install zustand zustand-valtio valtioUsage
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 is sweet?
Examples
The examples folder contains working examples. You can run one of them with
PORT=8080 pnpm run examples:01_counterand open http://localhost:8080 in your web browser.
You can also try them directly: 01 02 03 04