Trung BìnhState Management iconState Management

Cách định nghĩa actions trong Zustand store?

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:

  1. Partial update với set: increment: () => set(s => ({ count: s.count + 1 })).
  2. 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] })) }.
  3. 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' } })).

Xem toàn bộ State Management cùng filter theo level & chủ đề con.

Mở danh sách State Management