A sweet combination of Zustand and Valtio
npm install zustand zustand-valtio valtio
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>
</>
);
};
Zustand has immer
middleware to update state mutably.
Valtio has the same capability. Isn't the combination sweet?
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.