Server state với TanStack Query
Phân biệt server state và client state, query key, stale time, invalidation, mutation, optimistic update có rollback, phân trang, infinite scroll và prefetch.
Dữ liệu từ server không phải "state của bạn" — nó là bản sao có thể cũ của dữ liệu ở nơi khác. Tự quản lý bằng
useEffect + useState nghĩa là tự viết lại cache, dedupe, retry, refetch, đồng bộ giữa tab... TanStack Query giải
quyết phần này và là thư viện xuất hiện trong rất nhiều JD React.
🎯 Mục tiêu học tập
- Giải thích server state khác client state thế nào
- Thiết kế query key và query options dùng lại được
- Hiểu
staleTime,gcTime, refetch tự động - Viết mutation có invalidate hoặc cập nhật cache trực tiếp
- Làm optimistic update có rollback khi lỗi
Cài đặt và query đầu tiên
import { QueryClient, QueryClientProvider, useQuery, queryOptions } from '@tanstack/react-query';
const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 30_000, retry: 2 } },
});
// Gom query key + hàm fetch vào một chỗ, dùng lại cho useQuery, prefetch, invalidate
export const productQueries = {
all: () => ['products'] as const,
list: (f: { page: number; sort: string }) =>
queryOptions({ queryKey: [...productQueries.all(), 'list', f], queryFn: ({ signal }) => api.listProducts(f, signal) }),
detail: (id: string) =>
queryOptions({ queryKey: [...productQueries.all(), 'detail', id], queryFn: ({ signal }) => api.getProduct(id, signal) }),
};
function ProductDetail({ id }: { id: string }) {
const { data, isPending, isError, error, isFetching } = useQuery(productQueries.detail(id));
if (isPending) return <Skeleton />;
if (isError) return <ErrorBox error={error} />;
return <article>{data.name} {isFetching && <small>đang cập nhật…</small>}</article>;
}
Query key giống deps: mọi biến mà queryFn dùng phải có trong key. Đổi key = query khác, có cache riêng.
staleTime, gcTime và vòng đời cache
| Khái niệm | Ý nghĩa | Mặc định |
|---|---|---|
staleTime | Bao lâu dữ liệu được coi là còn mới — trong khoảng này không refetch | 0 |
gcTime | Bao lâu giữ cache khi không còn component nào dùng | 5 phút |
| Refetch tự động | Khi mount mới, focus lại cửa sổ, mạng có lại — chỉ khi dữ liệu đã stale | Bật |
Hiển thị cache cũ ngay rồi cập nhật nền (stale-while-revalidate) là lý do ứng dụng dùng Query cảm giác rất nhanh.
Dữ liệu ít đổi (danh mục, cấu hình) đặt staleTime vài phút tới vô hạn; dữ liệu nhạy thời gian (số dư) đặt thấp.
Mutation và invalidation
function useUpdateProduct() {
const qc = useQueryClient();
return useMutation({
mutationFn: api.updateProduct,
onSuccess: (updated) => {
qc.setQueryData(productQueries.detail(updated.id).queryKey, updated); // cập nhật cache chi tiết
qc.invalidateQueries({ queryKey: productQueries.all() }); // đánh dấu các list là stale
},
});
}
const { mutate, isPending } = useUpdateProduct();
<button disabled={isPending} onClick={() => mutate({ id, price: 99_000 })}>Lưu</button>
Optimistic update có rollback
function useToggleLike(postId: string) {
const qc = useQueryClient();
const key = ['post', postId];
return useMutation({
mutationFn: () => api.toggleLike(postId),
onMutate: async () => {
await qc.cancelQueries({ queryKey: key }); // tránh refetch cũ ghi đè
const previous = qc.getQueryData<Post>(key);
qc.setQueryData<Post>(key, p => p && { ...p, liked: !p.liked, likes: p.likes + (p.liked ? -1 : 1) });
return { previous };
},
onError: (_err, _vars, ctx) => qc.setQueryData(key, ctx?.previous), // rollback
onSettled: () => qc.invalidateQueries({ queryKey: key }), // đồng bộ lại với server
});
}
Optimistic phù hợp với thao tác gần như luôn thành công (like, đánh dấu đã đọc). Thanh toán, đặt chỗ thì không nên — hiển thị trạng thái đang xử lý rõ ràng.
Phân trang, infinite scroll, prefetch
// Phân trang: giữ trang cũ trong lúc tải trang mới, không nháy skeleton
const { data, isPlaceholderData } = useQuery({ ...productQueries.list({ page, sort }), placeholderData: keepPreviousData });
// Infinite scroll
const q = useInfiniteQuery({
queryKey: ['feed'],
queryFn: ({ pageParam, signal }) => api.feed({ cursor: pageParam, signal }),
initialPageParam: null as string | null,
getNextPageParam: last => last.nextCursor ?? undefined,
});
const items = q.data?.pages.flatMap(p => p.items) ?? [];
// Prefetch khi hover link
<Link to={`/products/${p.id}`} onMouseEnter={() => qc.prefetchQuery(productQueries.detail(p.id))}>{p.name}</Link>
useSuspenseQuery kết hợp với <Suspense> và Error Boundary (Module 18) để bỏ hẳn các nhánh isPending.
🚩 Sai lầm hay gặp
- Copy dữ liệu từ query vào
useStaterồi sửa — mất đồng bộ với cache. - Query key thiếu biến (ví dụ thiếu
page) → mọi trang dùng chung một cache. - Dùng TanStack Query cho state thuần client (modal đang mở) — dùng useState/Zustand.
🏋️ Bài tập thực hành
Danh sách có phân trang + sắp xếp (URL state), chi tiết, sửa (invalidate), xoá có optimistic + rollback (giả lập API lỗi 20% thời gian), prefetch khi hover, infinite scroll cho trang 'Mới nhất'. Mở React Query Devtools và giải thích vòng đời của từng query.
📚 Tài nguyên học tập
-
TanStack Query docsTài liệu chính thứcDocs
-
TkDodo's blogLoạt bài của maintainer, rất nên đọcBlog
✅ Tự đánh giá hoàn thành
- Tôi giải thích được server state vs client state
- Tôi phân biệt được
staleTimevàgcTime - Tôi viết được optimistic update có rollback
- Tôi thiết kế được query key factory