| name | react-state-management |
| description | null |
State Management
Category: react · Status: 🟢 Active
When to use
Khi quyết định đặt state ở đâu và chọn cơ chế quản lý phù hợp.
Steps
- Mặc định dùng local
useState; chỉ lift lên khi nhiều con cùng cần.
- Dùng Context cho state ít đổi, mang tính global (theme, auth, locale).
- Dùng store (Zustand/Redux) khi state phức tạp, chia sẻ rộng, cần devtools.
- Server state (API data) tách riêng cho react-query, không nhồi vào store UI.
- Derive value từ state nguồn thay vì lưu state thừa gây lệch đồng bộ.
Template
const [items, setItems] = useState<Item[]>([]);
const completed = items.filter((i) => i.done);
const total = items.length;
Example
Good: completedCount tính từ items; auth để Context; danh sách API qua react-query.
Avoid: Lưu completedCount thành state riêng rồi sync tay; nhồi server data vào Redux.
Checklist