Zustand Syntax & Conventions

Been experimenting with Zustand a bit and really liking the simplicity so far. Got a few questions regarding syntax and conventions(?). 1. For defining actions, do you do logic inside the set function or outside? i.e. which of these would you prefer?
export const useStore = create<Store>((set, get) => ({
count: 0,
decrement() {
const count = get().count;
console.log("sideeffect here", count);
set({ count: count - 1 });
},
increment() {
set((state) => {
console.log("sideeffect here", state.count);
return { count: state.count + 1 };
});
},
}));
export const useStore = create<Store>((set, get) => ({
count: 0,
decrement() {
const count = get().count;
console.log("sideeffect here", count);
set({ count: count - 1 });
},
increment() {
set((state) => {
console.log("sideeffect here", state.count);
return { count: state.count + 1 };
});
},
}));
2. Do you create multiple stores, namespace (if so how) the different categories of your store, or keep all in root? i.e. lets say i have a counter, and some messaging system. would you create one useCountStore and one useMessagesStore or one big store and keep like { count: { value, increment, decrement }, messages: { ... } } or just keep all state and actions in the root store object like { count, increment, decrement, listMessages ... }. I tried slicing like this: https://github.com/pmndrs/zustand/blob/main/docs/guides/typescript.md#slices-pattern but it places everything in the root, would something like this (but not this cause this doesn't work) be preferred?
const useBoundStore = create<BearSlice & FishSlice>()((...a) => ({
bear: createBearSlice(...a),
fish: createFishSlice(...a),
}))
const useBoundStore = create<BearSlice & FishSlice>()((...a) => ({
bear: createBearSlice(...a),
fish: createFishSlice(...a),
}))
3. For consuming the store, is performance affected a lot when grabbing the entire store when i need a few different keys, i.e. which of these is preffered:
// 1
const count = useStore(s => s.count);
const increment = useStore(s => s.increment);
const decrement = useStore(s => s.decrement);

// 2
const { count, increment, decrement } = useStore();

// 3
const { count, increment, decrement } = useStore(s => ({
count: s.count,
increment: s.increment,
decrement: s.decrement,
}));
// 1
const count = useStore(s => s.count);
const increment = useStore(s => s.increment);
const decrement = useStore(s => s.decrement);

// 2
const { count, increment, decrement } = useStore();

// 3
const { count, increment, decrement } = useStore(s => ({
count: s.count,
increment: s.increment,
decrement: s.decrement,
}));
1 Reply
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server