React từ cơ bản đến nâng cao
Trang chủ / Module 8
🗂️ Module 8 / 22 · 4 ngày 📅 Tuần 4 ●●○○ Trung bình

Context và useReducer cho state phức tạp

Gom logic cập nhật vào reducer, chia sẻ dữ liệu sâu bằng Context, tách context state/dispatch để giảm render, và mô hình hoá trạng thái như state machine.

useReducerContextImmerState machine
📌 Vì sao module này quan trọng

Khi một component có 6-7 useState và handler nào cũng sửa 3-4 cái cùng lúc, bug xuất hiện. Reducer gom toàn bộ quy tắc chuyển trạng thái về một chỗ, test được bằng hàm thuần. Context giải quyết dữ liệu dùng ở nhiều nơi (theme, user, locale) — nhưng dùng sai là cả cây render lại.

🎯 Mục tiêu học tập

  • Viết reducer thuần và action có kiểu rõ ràng
  • Kết hợp reducer + Context để chia sẻ state cho một khu vực của app
  • Giải thích khi nào Context làm render lại và cách giảm
  • Mô hình hoá trạng thái bằng state machine để loại bỏ trạng thái không hợp lệ

useReducer

type Item = { id: string; name: string; price: number; qty: number };
type State = { items: Item[]; coupon: string | null };
type Action =
  | { type: 'added'; item: Omit<Item, 'qty'> }
  | { type: 'qtyChanged'; id: string; qty: number }
  | { type: 'removed'; id: string }
  | { type: 'couponApplied'; code: string };

function cartReducer(state: State, action: Action): State {
  switch (action.type) {
    case 'added': {
      const exists = state.items.find(i => i.id === action.item.id);
      return {
        ...state,
        items: exists
          ? state.items.map(i => i.id === action.item.id ? { ...i, qty: i.qty + 1 } : i)
          : [...state.items, { ...action.item, qty: 1 }],
      };
    }
    case 'qtyChanged':
      return { ...state, items: state.items.map(i => i.id === action.id ? { ...i, qty: Math.max(1, action.qty) } : i) };
    case 'removed':
      return { ...state, items: state.items.filter(i => i.id !== action.id) };
    case 'couponApplied':
      return { ...state, coupon: action.code };
    default: {
      const _exhaustive: never = action;   // TS báo lỗi nếu quên xử lý action
      return state;
    }
  }
}

const [cart, dispatch] = useReducer(cartReducer, { items: [], coupon: null });
dispatch({ type: 'added', item: { id: 'p1', name: 'Áo', price: 200_000 } });

Đặt tên action theo chuyện đã xảy ra (added, qtyChanged) thay vì lệnh (setItems). Reducer là hàm thuần nên test không cần render: expect(cartReducer(s, a)).toEqual(...).

Immer khi state lồng sâu

import { useImmerReducer } from 'use-immer';

function reducer(draft: State, action: Action) {
  switch (action.type) {
    case 'qtyChanged': {
      const item = draft.items.find(i => i.id === action.id);
      if (item) item.qty = action.qty;     // trông như mutate, Immer tạo object mới
      break;
    }
  }
}

Context: truyền dữ liệu không qua props

const CartStateContext = createContext<State | null>(null);
const CartDispatchContext = createContext<React.Dispatch<Action> | null>(null);

export function CartProvider({ children }: { children: React.ReactNode }) {
  const [state, dispatch] = useReducer(cartReducer, { items: [], coupon: null });
  return (
    <CartStateContext value={state}>
      <CartDispatchContext value={dispatch}>{children}</CartDispatchContext>
    </CartStateContext>
  );
}

export function useCart() {
  const ctx = useContext(CartStateContext);
  if (!ctx) throw new Error('useCart phải nằm trong <CartProvider>');
  return ctx;
}
export function useCartDispatch() {
  const ctx = useContext(CartDispatchContext);
  if (!ctx) throw new Error('useCartDispatch phải nằm trong <CartProvider>');
  return ctx;
}

Tách hai context: nút "Thêm vào giỏ" chỉ cần dispatch (không bao giờ đổi), nên không render lại khi giỏ hàng thay đổi.

Context và hiệu năng

Mọi component gọi useContext(X) sẽ render lại khi value của X đổi tham chiếu. Ba bẫy và cách xử lý:

BẫyCách xử lý
value={{ user, setUser }} tạo object mới mỗi lần Provider renderuseMemo cho value (hoặc để React Compiler lo)
Một context khổng lồ chứa mọi thứTách theo tần suất thay đổi: theme, auth, cart riêng
Component chỉ cần 1 field nhưng render lại khi field khác đổiContext không hỗ trợ selector → chuyển sang store có selector (Zustand, Module 14) hoặc useSyncExternalStore

Context phù hợp cho dữ liệu ít thay đổi (theme, locale, user đăng nhập, dependency injection). Dữ liệu thay đổi liên tục và nhiều nơi đọc thì dùng store chuyên dụng.

State machine: loại bỏ trạng thái không thể xảy ra

type FetchState<T> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; error: Error };

function render(s: FetchState<User>) {
  switch (s.status) {
    case 'loading': return <Spinner />;
    case 'error':   return <ErrorBox error={s.error} />;   // TS biết chắc có error
    case 'success': return <UserCard user={s.data} />;     // TS biết chắc có data
    default:        return null;
  }
}

Với 3 boolean isLoading/isError/isSuccess có 8 tổ hợp, chỉ 4 hợp lệ. Discriminated union chỉ cho phép 4. Luồng phức tạp hơn (checkout nhiều bước, upload có retry) có thể dùng XState.

🚩 Sai lầm hay gặp

  • Quên kiểm tra Provider → useContext trả về giá trị mặc định, bug im lặng. Luôn bọc bằng hook throw lỗi.
  • Mutate state trong reducer rồi return chính nó — UI không cập nhật.
  • Dùng Context làm 'Redux tự chế' cho dữ liệu đổi mỗi giây.

🏋️ Bài tập thực hành

Giỏ hàng có mã giảm giá

Giỏ hàng với reducer + 2 context. Tính tạm tính, giảm giá, phí ship (miễn phí trên 500.000đ) bằng hàm thuần. Viết 10 unit test cho reducer. Dùng React DevTools 'Highlight updates' để chứng minh nút 'Thêm' không render lại khi đổi số lượng.

📚 Tài nguyên học tập

✅ Tự đánh giá hoàn thành

  • Tôi viết reducer có kiểu đầy đủ và kiểm tra exhaustive bằng never
  • Tôi giải thích được khi nào Context gây render lại
  • Tôi tách được state/dispatch context và biết vì sao
  • Tôi dùng discriminated union thay cho nhiều boolean