Global state: Zustand, Redux Toolkit, Jotai — chọn thế nào
Phân loại state, khi nào thật sự cần global store, Zustand với selector, Redux Toolkit cho dự án lớn, Jotai cho state dạng atom, và tiêu chí chọn.
Nhiều dự án cài Redux từ ngày đầu rồi nhét cả dữ liệu server vào đó. Sau khi tách server state sang TanStack Query, phần global state còn lại thường rất nhỏ. Biết phân loại state giúp bạn chọn công cụ đơn giản nhất đủ dùng — và trả lời tốt câu "vì sao chọn X" khi phỏng vấn.
🎯 Mục tiêu học tập
- Phân loại state: local, shared UI, server, URL, form
- Dùng Zustand với selector để tránh render thừa
- Hiểu Redux Toolkit: slice, store, RTK Query
- Biết khi nào Jotai phù hợp
Bản đồ state
| Loại | Ví dụ | Công cụ |
|---|---|---|
| Local UI | Dropdown đang mở, input đang gõ | useState |
| Server state | Danh sách sản phẩm, profile | TanStack Query / framework loader |
| URL state | Bộ lọc, trang, tab | Router search params |
| Form state | Giá trị và lỗi form | RHF / form action |
| Shared client state | Giỏ hàng chưa đăng nhập, theme, editor state, player nhạc | Context (ít đổi) / Zustand / Redux / Jotai |
Zustand
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
type CartStore = {
items: Record<string, number>;
add: (id: string) => void;
remove: (id: string) => void;
clear: () => void;
};
export const useCartStore = create<CartStore>()(
persist(
set => ({
items: {},
add: id => set(s => ({ items: { ...s.items, [id]: (s.items[id] ?? 0) + 1 } })),
remove: id => set(s => { const { [id]: _, ...rest } = s.items; return { items: rest }; }),
clear: () => set({ items: {} }),
}),
{ name: 'cart' }, // lưu localStorage
),
);
// Chỉ render lại khi số lượng của id này đổi
const qty = useCartStore(s => s.items[id] ?? 0);
const add = useCartStore(s => s.add);
// Lấy nhiều giá trị: dùng useShallow để không render lại khi object mới nhưng nội dung giống
const { items, clear } = useCartStore(useShallow(s => ({ items: s.items, clear: s.clear })));
// Ngoài React (interceptor, websocket handler)
useCartStore.getState().clear();
Zustand nhỏ, không cần Provider, có selector — lựa chọn mặc định tốt cho hầu hết dự án mới.
Redux Toolkit
import { createSlice, configureStore, type PayloadAction } from '@reduxjs/toolkit';
const cartSlice = createSlice({
name: 'cart',
initialState: { items: {} as Record<string, number> },
reducers: {
added(state, action: PayloadAction<string>) {
state.items[action.payload] = (state.items[action.payload] ?? 0) + 1; // Immer bên dưới
},
},
});
export const { added } = cartSlice.actions;
export const store = configureStore({ reducer: { cart: cartSlice.reducer } });
export type RootState = ReturnType<typeof store.getState>;
Redux mạnh ở dự án lớn nhiều team: quy ước chặt, DevTools time-travel, middleware, RTK Query cho server state. Đổi lại nhiều boilerplate hơn. Gặp nhiều trong dự án có sẵn (legacy) — cần đọc hiểu được.
Jotai: state dạng atom
import { atom, useAtom, useAtomValue } from 'jotai';
const priceAtom = atom(100);
const qtyAtom = atom(2);
const totalAtom = atom(get => get(priceAtom) * get(qtyAtom)); // derived atom
function Total() { return <p>{useAtomValue(totalAtom)}</p>; } // chỉ render khi total đổi
Hợp với state dạng đồ thị phụ thuộc nhiều mảnh nhỏ: editor, canvas, form builder.
Tiêu chí chọn
| Tiêu chí | Context | Zustand | Redux Toolkit | Jotai |
|---|---|---|---|---|
| Kích thước / học | 0 / dễ | Rất nhỏ / dễ | Trung bình / vừa | Nhỏ / dễ |
| Selector chống render thừa | Không | Có | Có | Theo atom |
| DevTools | React DevTools | Qua middleware | Rất mạnh | Có |
| Hợp nhất cho | Theme, auth, DI | Đa số app | App lớn, nhiều team, legacy | State dạng đồ thị |
Với SSR (Next.js), store toàn cục ở cấp module bị chia sẻ giữa các request trên server → lộ dữ liệu giữa người dùng. Phải tạo store theo request (store trong Provider). Xem khoá Next.js.
🚩 Sai lầm hay gặp
- Đưa dữ liệu server vào Redux/Zustand rồi tự viết loading/cache.
- Selector trả về object mới mỗi lần mà không dùng
useShallow→ render liên tục. - Store cấp module dùng trong SSR → rò rỉ dữ liệu giữa người dùng.
🏋️ Bài tập thực hành
Làm giỏ hàng bằng Context+reducer, Zustand và Redux Toolkit. Đo số lần render bằng Profiler khi thêm sản phẩm, so sánh lượng code. Viết một trang README nêu bạn chọn cái nào cho dự án 5 người và vì sao.
📚 Tài nguyên học tập
-
ZustandTài liệuDocs
-
Redux ToolkitTài liệuDocs
-
JotaiTài liệuDocs
✅ Tự đánh giá hoàn thành
- Tôi phân loại được state của một màn hình bất kỳ
- Tôi dùng Zustand với selector đúng cách
- Tôi đọc hiểu được code Redux Toolkit
- Tôi giải thích được rủi ro store toàn cục khi SSR