</>
⌕
Senior #state-management#redux#zustand#react-query

Chọn state management: useState, Context, Redux, Zustand, React Query?

⚡ Trả lời nhanh

Phân loại state trước: UI cục bộ dùng useState; server state (cache, refetch, đồng bộ) dùng React Query/SWR; client state toàn cục dùng Zustand (gọn) hoặc Redux Toolkit (app lớn, cần devtools, quy ước chặt). Context hợp cho giá trị ít đổi như theme.

Loại stateCông cụLý do
Cục bộ (input, modal)useState/useReducerĐơn giản nhất
Server stateReact Query, SWR, RTK QueryCache, dedupe, refetch, retry, stale-while-revalidate
Global client stateZustand, JotaiÍt boilerplate, có selector
Global phức tạp, team lớnRedux ToolkitLuồng một chiều, devtools time-travel, middleware
Giá trị ít đổi (theme, locale, user)ContextKhông thêm thư viện
State trong URLRouter search paramsChia sẻ link, back/forward
const useCart = create(set => ({
  items: [],
  add: item => set(s => ({ items: [...s.items, item] })),
}));
const count = useCart(s => s.items.length); // chỉ re-render khi count đổi
🃏 Ôn bằng flashcard