-
Hello, I've been trying 3 different ways of consuming state in Zustand. Considering this simple store: import create from "zustand";
type State = {
bears: number;
hunters: number
};
export const bearStore = create((set: Partial<State>) => ({
bears: 0,
hunters: 3
}));
const moreBears = (count: number) => {
return bearStore.setState((store) => ({
bears: store.bears + count
}));
};
const moreHunters = (count: number) => {
return bearStore.setState((store) => ({
hunters: store.hunters + count
}));
};
export const bearControler = {
moreBears,
moreHunters
}; Is there a performance difference between this short import: const { bears, hunters } = bearStore((state)=> state, shallow); and the official documentation import: const { bears, hunters } = bearStore(
(state) => ({ bears: state.bears, hunters: state.hunters }),
shallow
); Also, I'm wondering if shallow comparison is a must-have? From a performance perspective, is this short import ok (it avoids me to import const { bears, hunters } = bearStore() Thank you for your advice! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
the first triggers on every state update, but if im not mistaken it carries out unnecessary checks for each top level state prop which isn't good. all components using that will render. the slowest. the second will trigger once bears and/or hunters are changed, it will bail out on everything else. the third triggers on every state update, but it's still just a single check (oldState === newState). all components using that will render. hooks should start with "use" - no linter would let "bearStore" pass, that's just conventions though. |
Beta Was this translation helpful? Give feedback.
the first triggers on every state update, but if im not mistaken it carries out unnecessary checks for each top level state prop which isn't good. all components using that will render. the slowest.
the second will trigger once bears and/or hunters are changed, it will bail out on everything else.
the third triggers on every state update, but it's still just a single check (oldState === newState). all components using that will render.
hooks should start with "use" - no linter would let "bearStore" pass, that's just conventions though.