Server state, client state & forms: TanStack Query, Zustand, React Hook Form
Tách bạch server state và client state: cache, invalidation, optimistic update, infinite scroll bằng TanStack Query; state toàn cục tối giản bằng Zustand; form phức tạp với React Hook Form + Zod dùng chung schema với backend.
80% "state management" trong app thực tế là dữ liệu từ server — và nó cần cache, dedupe, refetch khi focus, invalidation sau mutation, xử lý loading/error. Tự làm bằng useEffect + Redux là hàng nghìn dòng code dễ sai. Dùng đúng công cụ cho đúng loại state làm codebase nhỏ đi một nửa và xoá cả một lớp bug.
🎯 Mục tiêu học tập
- Dùng TanStack Query: query key, staleTime, invalidation, prefetch
- Cài optimistic update có rollback và infinite query
- Quản lý state toàn cục tối thiểu bằng Zustand; đưa filter/tab lên URL
- Xây form phức tạp (mảng field, field phụ thuộc) bằng React Hook Form + Zod
- Sinh API client type-safe từ OpenAPI hoặc dùng tRPC
TanStack Query: cache server state
// Query key factory — một nơi định nghĩa, tránh gõ sai
export const taskKeys = {
all: ['tasks'] as const,
list: (projectId: string, filters: TaskFilters) => ['tasks', 'list', projectId, filters] as const,
detail: (id: string) => ['tasks', 'detail', id] as const,
};
export function useTasks(projectId: string, filters: TaskFilters) {
return useQuery({
queryKey: taskKeys.list(projectId, filters),
queryFn: ({ signal }) => api.tasks.list(projectId, filters, { signal }), // tự huỷ request cũ
staleTime: 30_000, // 30s coi là mới, không refetch
placeholderData: keepPreviousData // đổi filter không nhấp nháy về trạng thái loading
});
}
| Khái niệm | Ý nghĩa |
|---|---|
staleTime | Bao lâu dữ liệu được coi là mới (mặc định 0 → refetch khi mount/focus) |
gcTime | Bao lâu giữ cache khi không còn ai dùng |
| Dedupe | 10 component cùng query key → 1 request |
invalidateQueries | Đánh dấu cũ và refetch sau mutation |
Mutation, optimistic update, infinite query
export function useMoveTask(projectId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: api.tasks.move,
onMutate: async (vars) => {
await qc.cancelQueries({ queryKey: ['tasks', 'list', projectId] });
const prev = qc.getQueriesData({ queryKey: ['tasks', 'list', projectId] });
qc.setQueriesData({ queryKey: ['tasks', 'list', projectId] }, (old: Task[] = []) =>
old.map((t) => (t.id === vars.id ? { ...t, status: vars.status } : t)));
return { prev };
},
onError: (_e, _v, ctx) => ctx?.prev.forEach(([key, data]) => qc.setQueryData(key, data)), // rollback
onSettled: () => qc.invalidateQueries({ queryKey: ['tasks', 'list', projectId] }),
});
}
// Infinite scroll với cursor pagination của Module 4
useInfiniteQuery({
queryKey: ['activity', orgId],
queryFn: ({ pageParam }) => api.activity.list({ cursor: pageParam }),
initialPageParam: undefined as string | undefined,
getNextPageParam: (last) => last.pageInfo.hasMore ? last.pageInfo.nextCursor : undefined,
});
Kết hợp realtime (Module 9): khi nhận sự kiện task:updated qua socket, gọi
setQueryData hoặc invalidateQueries — không cần store riêng.
Client state: Zustand và URL
// Zustand cho state UI toàn cục thật sự (sidebar, theme, lựa chọn nhiều item)
export const useUiStore = create<UiState>()((set) => ({
sidebarOpen: true,
toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })),
}));
const open = useUiStore((s) => s.sidebarOpen); // selector → chỉ render khi field này đổi
// Filter, tab, trang, từ khoá tìm kiếm → URL (chia sẻ link, back/forward hoạt động)
// Dùng useSearchParams của router hoặc thư viện nuqs để có kiểu và parse
Redux Toolkit vẫn gặp nhiều trong codebase doanh nghiệp — học đủ để đọc và bảo trì (slice, RTK Query), nhưng dự án mới thường không cần.
Form: React Hook Form + Zod dùng chung schema
import { CreateTaskSchema, type CreateTaskInput } from '@app/contracts'; // cùng schema backend dùng
const form = useForm<CreateTaskInput>({
resolver: zodResolver(CreateTaskSchema),
defaultValues: { title: '', checklist: [] },
});
const { fields, append, remove } = useFieldArray({ control: form.control, name: 'checklist' });
const onSubmit = form.handleSubmit(async (data) => {
const res = await createTask.mutateAsync(data);
if (!res.ok && res.error.code === 'VALIDATION_ERROR') {
// map lỗi server về đúng field
Object.entries(res.error.details.fieldErrors).forEach(([k, msg]) => form.setError(k as any, { message: msg[0] }));
}
});
- RHF dùng uncontrolled input → form 50 field vẫn mượt.
- Luôn hiển thị lỗi server bên cạnh field; disable nút khi đang gửi; giữ dữ liệu khi lỗi mạng.
- Với Next.js Server Actions (Module 12), có thể dùng form +
useActionStatevà validate Zod ở server — progressive enhancement.
API client type-safe
| Cách | Khi dùng |
|---|---|
openapi-typescript + openapi-fetch | Backend riêng (NestJS) có OpenAPI — sinh type tự động trong CI |
| Orval / Hey API | Sinh luôn hook TanStack Query từ OpenAPI |
| tRPC | Monorepo TS, frontend và backend cùng team |
Package contracts chung (Zod) | Monorepo; schema dùng cho cả validate server lẫn form |
Mục tiêu: backend đổi tên một field → frontend lỗi biên dịch ngay, không phải lỗi runtime trên production.
🏋️ Bài tập thực hành
Thay dữ liệu giả bằng API của bạn: (1) Sinh client từ OpenAPI của backend. (2) Toàn bộ dữ liệu server qua TanStack Query với query key factory. (3) Kéo thả task giữa các cột với optimistic update + rollback (giả lập server lỗi 30% để kiểm tra). (4) Feed hoạt động infinite scroll. (5) Filter board lưu trên URL. (6) Form tạo task có checklist động (useFieldArray), validate bằng schema dùng chung, hiển thị lỗi 400 từ server đúng field. (7) Nhận sự kiện socket và cập nhật cache.
📚 Tài nguyên học tập
-
TanStack Query DocsTài liệu chính thứcDocs
-
TkDodo's blogLoạt bài 'Practical React Query' của maintainerArticle
-
ZustandState management tối giảnDocs
-
React Hook FormForm hiệu năng caoDocs
-
openapi-typescriptSinh type và client từ OpenAPIDocs
-
nuqsState trên URL search params có kiểuDocs
✅ Tự đánh giá hoàn thành
- Phân loại đúng server/URL/form/UI state trong app
- Có optimistic update với rollback hoạt động
- Form phức tạp dùng schema chung với backend
- Đổi field ở backend làm frontend lỗi biên dịch