Four slice patterns #2647
Replies: 3 comments 2 replies
-
Simplified Bear Zustandimport { create, StateCreator } from "zustand";
interface CountSlice {
count: number;
incCount: () => void;
resetCount: () => void;
}
interface TextSlice {
text: string;
updateText: (newText: string) => void;
resetText: () => void;
}
interface SharedSlice {
reset: () => void;
}
const createCountSlice: StateCreator<CountSlice> = (set) => ({
count: 0,
incCount: () => set((state) => ({ count: state.count + 1 })),
resetCount: () => set({ count: 0 }),
});
const createTextSlice: StateCreator<TextSlice> = (set) => ({
text: "Hello",
updateText: (text) => set({ text }),
resetText: () => set({ text: "Hello" }),
});
const useCounterStore = create<CountSlice & TextSlice & SharedSlice>()(
(set, get, api) => ({
...createCountSlice(set, get, api),
...createTextSlice(set, get, api),
reset: () => {
get().resetCount();
get().resetText();
},
}),
); |
Beta Was this translation helpful? Give feedback.
-
Poll: https://x.com/dai_shi/status/1812649338654617918 Similar discussion: #2672 |
Beta Was this translation helpful? Give feedback.
-
@dai-shi maybe this is a little crazy, but I did what I think is a useful and very scaleable slice pattern in zustand-namespaces. Here is an example: import { create } from 'zustand';
import {
namespaced,
createNamespace,
getNamespaceHooks,
} from 'zustand-namespaces';
const namespaceA = createNamespace('namespaceA', () => ({
dataInNamespaceA: 'data',
}));
const namespaceB = createNamespace('namespaceB', () => ({
dataInNamespaceB: 'data',
}));
const useStore = create(
namespaced(
// Namespaced state is passed as an argument for you to use in your store
(namespacedState) => () => ({
mainData: 'data',
...namespacedState,
}),
{
namespaces: [namespaceA, namespaceB],
}
)
);
export const { namespaceA: useNamespaceA, namespaceB: useNamespaceB } =
getNamespaceHooks(useStore, namespaceA, namespaceB); It namespaces data (hence the name), allows for middleware within each slice while still only being one store, and you can have as many levels of nested namespaces as you want. It has a few more tricks up its sleeve if you read the docs on github What are your thoughts on this approach? |
Beta Was this translation helpful? Give feedback.
-
Bare (Bear) Zustand
https://tsplay.dev/NaAE6N
Zustand Lens
https://tsplay.dev/Wz1GEm
Zustand Slices
https://tsplay.dev/mxOkXN
Zustand Valtio
https://tsplay.dev/wQdRAW
Beta Was this translation helpful? Give feedback.
All reactions