Dùng create từ 'zustand', truyền vào initializer function nhận (set, get) và trả về object chứa cả state lẫn actions 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.
Ví dụ đầy đủ: 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 })).
Use create from 'zustand', passing an initializer function that receives (set, get) and returns an object containing both state and actions in one place. set() merges partial state (no need to spread everything like in Redux). get() reads the current state from within an action.
- Full example:
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 })). - The store returns a React hook, used directly:
const items = useCartStore(s => s.items)orconst addItem = useCartStore(s => s.addItem). - No Provider, no dispatch — call actions like regular functions:
addItem(product). - Compared to Redux: one Zustand slice file replaces actions + actionTypes + reducer + selectors + thunks.