Loading...
Loading...
Expert guide for Zustand state management patterns, store organization, and best practices. Use when implementing client state management with Zustand, creating stores, or managing shared UI state across components.
npx skill4agent add pedronauck/skills zustandreferences/patterns.mdimport { create } from "zustand";
import { devtools, persist } from "zustand/middleware";
import { immer } from "zustand/middleware/immer";
export const useExampleStore = create<ExampleState>()(
devtools(
persist(
immer((set, get) => ({
// state and actions
})),
{ name: "example-storage" }
),
{ name: "example-store" }
)
);interface StoreState {
// State properties
data: DataType | null;
isLoading: boolean;
// Group actions together
actions: {
fetchData: () => Promise<void>;
updateData: (updates: Partial<DataType>) => void;
reset: () => void;
};
}// Bad - subscribes to entire store
const { user, isLoading } = useAuthStore();
// Good - subscribes only to specific slices
export const useUser = () => useAuthStore((state) => state.user);
export const useIsLoading = () => useAuthStore((state) => state.isLoading);
export const useAuthActions = () => useAuthStore((state) => state.actions);partializepersistpartializepersist(
(set) => ({ /* ... */ }),
{
name: "store-key",
partialize: (state) => ({
// Only persist these fields
user: state.user,
preferences: state.preferences,
}),
}
);immer((set) => ({
updateNested: (id, value) => {
set((state) => {
const item = state.items.find((i) => i.id === id);
if (item) {
item.value = value; // Mutable style, but produces immutable state
}
});
},
}));actionspnpm run typecheckpnpm run testreferences/patterns.md