Dùng create từ 'zustand', truyền vào initializer nhận (set, get) và trả về object chứa cả state lẫn action trong cùng một chỗ. set() merge partial state (không cần spread toàn bộ như Redux), get() đọc state hiện tại từ bên trong action.
ts
const useCartStore = create((set, get) => ({
items: [],
total: 0,
addItem: (item) => set((s) => ({
items: [...s.items, item],
total: s.total + item.price,
})),
clearCart: () => set({ items: [], total: 0 }),
getItemCount: () => get().items.length,
}))Store trả về là một React hook, dùng thẳng trong component:
ts
const items = useCartStore((s) => s.items)
const addItem = useCartStore((s) => s.addItem)
addItem(product)Không cần Provider, không cần dispatch — gọi action như gọi function bình thường.
So với Redux: một file slice Zustand thay được cả actions + actionTypes + reducer + selectors + thunk.