Actions trong Zustand là plain functions sống cùng state trong store object — không có action types, không dispatch, không reducers.
Có 3 pattern chính:
- Partial update với set:
increment: () => set(s => ({ count: s.count + 1 })). - Computed values dùng get() để đọc state hiện tại bên trong action:
addItem: (item) => { const existing = get().items.find(i => i.id === item.id); set(s => ({ items: existing ? s.items.map(i => i.id === item.id ? {...i, qty: i.qty+1} : i) : [...s.items, item] })) }. - Async actions — không cần thunk middleware, viết async/await trực tiếp:
fetchUser: async (id) => { set({ loading: true }); const user = await api.getUser(id); set({ user, loading: false }) }
Multiple state updates trong một set call tự động batched.
Pitfall: set merge shallow — nested object phải tự spread: set(s => ({ config: { ...s.config, theme: 'dark' } })).