Zustand
Best practice-ek
Fókuszált store-ok, selectorok, logika a store-ban, derivált értékek, TypeScript és mappastruktúra.
Best practice-ek
1) Kis, fókuszált store-ok
useAuthStore, useCartStore, useUIStore2) Selector minden olvasásnál
const username = useAuthStore((state) => state.user?.name)3) Logika a store-ban
const useCartStore = create((set, get) => ({
items: [],
addItem: (product) => {
const existing = get().items.find((i) => i.id === product.id)
if (existing) {
set((state) => ({
items: state.items.map((i) =>
i.id === product.id ? { ...i, quantity: i.quantity + 1 } : i
),
}))
return
}
set((state) => ({ items: [...state.items, { ...product, quantity: 1 }] }))
},
}))4) Derivált értékeket selectorban számolj
const totalItems = useCartStore((state) =>
state.items.reduce((sum, item) => sum + item.quantity, 0)
)5) TypeScript interface legyen mindig
const useStore = create<StoreState>((set) => ({}))6) Ajánlott mappastruktúra
src/
stores/
useAuthStore.ts
useCartStore.ts
useUIStore.ts
index.ts