Fullstack Python
Trang chủ / Module 12
⚛️ Module 12 / 19 · 5 ngày 📅 Tuần 8-9 ●●●○ Khó

React cho fullstack Python: component, hooks, TanStack Query, form, router

React đủ sâu để xây giao diện sản phẩm thật trên backend Python: mô hình render và hooks, useEffect đúng cách, TanStack Query cho dữ liệu server (cache, invalidation, optimistic update), form với React Hook Form + Zod hiển thị lỗi 422 từ FastAPI, router, xác thực cookie, và khi nào cần Next.js.

React 19HooksTanStack QueryReact Hook FormZodRouter
📌 Vì sao module này quan trọng

React là thư viện frontend được tuyển dụng nhiều nhất toàn cầu, và cặp "FastAPI/Django + React" là stack fullstack Python phổ biến nhất ở công ty trả lương cao. Sai lầm điển hình của backend developer khi viết React là dùng useEffect cho mọi thứ và tự quản lý loading/error/cache bằng tay — sinh bug race condition và hàng trăm dòng code thừa. TanStack Query giải quyết gần hết phần đó.

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

  • Hiểu render, state, props, key, khi nào component render lại
  • Dùng useEffect chỉ để đồng bộ với hệ thống ngoài; tránh effect thừa
  • Quản lý dữ liệu server bằng TanStack Query: query key, invalidation, optimistic update, infinite query
  • Xây form với React Hook Form + Zod, map lỗi 422 của FastAPI vào field
  • Router, route bảo vệ, xác thực bằng cookie; biết khi nào chọn Next.js

Mô hình React và hooks

function TaskBoard({ projectId }: { projectId: number }) {
  const [filter, setFilter] = useState<'all' | 'open'>('all');
  const { data: tasks = [], isPending, error } = useTasks(projectId);          // TanStack Query
  const visible = filter === 'all' ? tasks : tasks.filter((t) => t.status !== 'done');   // tính khi render, không cần state/effect

  if (isPending) return <BoardSkeleton />;
  if (error) return <ErrorState onRetry={() => location.reload()} />;
  return (
    <>
      <FilterTabs value={filter} onChange={setFilter} />
      {visible.map((t) => <TaskCard key={t.id} task={t} />)}       {/* key ổn định, không dùng index */}
    </>
  );
}
  • Component render lại khi state của nó đổi hoặc cha render lại; state cập nhật bằng giá trị mới (bất biến).
  • useEffect chỉ để đồng bộ với hệ thống ngoài (WebSocket, document title, thư viện DOM) và luôn có cleanup. Dữ liệu dẫn xuất tính khi render; dữ liệu server dùng TanStack Query.
  • Custom hook (useTasks, useDebouncedValue) để tái sử dụng logic.
  • React 19: Actions, useActionState, useOptimistic; React Compiler giảm nhu cầu memo thủ công.

TanStack Query: dữ liệu server

export const taskKeys = {
  list: (projectId: number) => ['tasks', projectId] as const,
};

export function useTasks(projectId: number) {
  return useQuery({
    queryKey: taskKeys.list(projectId),
    queryFn: async ({ signal }) => {
      const { data, error } = await api.GET('/v1/projects/{project_id}/tasks', { params: { path: { project_id: projectId } }, signal });
      if (error) throw error;
      return data.data;
    },
    staleTime: 30_000,
  });
}

export function useMoveTask(projectId: number) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (v: { id: string; status: Task['status'] }) => api.PATCH('/v1/tasks/{task_id}', { params: { path: { task_id: v.id } }, body: { status: v.status } }),
    onMutate: async (v) => {                                     // optimistic update
      await qc.cancelQueries({ queryKey: taskKeys.list(projectId) });
      const prev = qc.getQueryData<Task[]>(taskKeys.list(projectId));
      qc.setQueryData<Task[]>(taskKeys.list(projectId), (old = []) => old.map((t) => (t.id === v.id ? { ...t, status: v.status } : t)));
      return { prev };
    },
    onError: (_e, _v, ctx) => qc.setQueryData(taskKeys.list(projectId), ctx?.prev),   // rollback
    onSettled: () => qc.invalidateQueries({ queryKey: taskKeys.list(projectId) }),
  });
}

Nhận sự kiện WebSocket từ backend (Module 10) → setQueryData hoặc invalidateQueries; không cần Redux. State UI toàn cục thật sự (sidebar, theme) dùng Zustand; filter/tab đưa lên URL.

Form và lỗi validate từ FastAPI

const schema = z.object({ title: z.string().trim().min(1, 'Bắt buộc').max(200), assignee_id: z.number().nullable() });
type FormValues = z.infer<typeof schema>;

const form = useForm<FormValues>({ resolver: zodResolver(schema), defaultValues: { title: '', assignee_id: null } });

const onSubmit = form.handleSubmit(async (values) => {
  const { error, response } = await api.POST('/v1/projects/{project_id}/tasks', { params: { path: { project_id } }, body: values });
  if (response.status === 422 && error) {
    for (const d of error.detail ?? []) {              // FastAPI: [{loc: ["body","title"], msg: "..."}]
      form.setError(d.loc.at(-1) as keyof FormValues, { message: d.msg });
    }
    return;
  }
  qc.invalidateQueries({ queryKey: taskKeys.list(project_id) });
});

Validate ở client cho trải nghiệm tốt; validate thật vẫn ở Pydantic. Disable nút khi đang gửi, giữ dữ liệu khi lỗi mạng.

Router, xác thực, và khi nào chọn Next.js

  • Router: React Router hoặc TanStack Router (có kiểu cho params, loader); route bảo vệ đọc trạng thái từ query /me.
  • Xác thực SPA với FastAPI/Django: session/refresh trong cookie HttpOnly, cùng domain gốc (hoặc proxy /api), CSRF token cho thao tác ghi; không lưu token trong localStorage.
  • Next.js khi cần SEO/SSR cho trang công khai, hoặc muốn tầng BFF; khi đó Next.js gọi FastAPI từ server. Dashboard sau đăng nhập thì SPA Vite thường đủ và đơn giản hơn.

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

Frontend capstone bằng React + TanStack Query

(1) Trang danh sách project, board Kanban kéo thả (dnd-kit) với optimistic update + rollback (giả lập server lỗi 30%). (2) Form tạo task có hiển thị lỗi 422 đúng field. (3) Feed hoạt động infinite scroll với cursor pagination. (4) Bộ lọc trên URL. (5) WebSocket cập nhật cache khi người khác sửa. (6) Đăng nhập bằng cookie HttpOnly + CSRF; route bảo vệ. Không có useEffect nào ngoài đồng bộ hệ thống ngoài.

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

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

  • Không dùng useEffect cho dữ liệu dẫn xuất hay fetch
  • Dữ liệu server qua TanStack Query, có optimistic update + rollback
  • Form hiển thị lỗi 422 của FastAPI đúng field
  • Xác thực bằng cookie HttpOnly, biết khi nào cần Next.js