Are actions part of the state? #2813
-
I feel like I'm going crazy. There is no difference between an "action" in zustand and a function that is just on the state, right? The actions themselves are part of the state, right? ChatGPT refuses to admit it: https://chatgpt.com/share/67199266-7fbc-800b-9d13-4a372c94221b Is this good design? It feels very wrong. > import { create } from 'npm:zustand'
const useBearStore = create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
mutilate: () => set({ increasePopulation: () => set((state) => ({ bears: NaN })) }), // ruin everything
}));
undefined
> useBearStore.getState().bears
0
> useBearStore.getState().increasePopulation()
undefined
> useBearStore.getState().bears
1
> useBearStore.getState().mutilate() // chaos & destruction
undefined
> useBearStore.getState().increasePopulation()
undefined
> useBearStore.getState().bears // death
NaN
> |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I can understand that and propose this: But, in general people like store (state) actions. I think one reason is that it's the same idea with const useCount = () => {
const [count, setCount] = useState(0);
return {
count,
inc: () => setCount((prev) => prev + 1),
};
}; Maybe, some middleware that prevent overwriting state functions might be possible. |
Beta Was this translation helpful? Give feedback.
I can understand that and propose this:
zustand/docs/guides/practice-with-no-store-actions.md
Line 2 in f9b5538
But, in general people like store (state) actions.
I think one reason is that it's the same idea with
useState
. People are very used to this pattern:Maybe, some middleware that prevent overwriting state functions might be possible.