Mid #react-query#data-fetching#cache
TanStack Query: staleTime, gcTime, invalidate và vì sao khác tự gọi fetch trong useEffect?
⚡ Trả lời nhanh
TanStack Query quản lý server state: cache theo `queryKey`, dedupe request, retry, refetch nền. `staleTime` là thời gian dữ liệu coi là tươi (mặc định 0); `gcTime` (v5; trước là cacheTime, mặc định 5 phút) là thời gian giữ cache khi không còn observer. Sau mutation dùng `invalidateQueries`.
const { data, isPending } = useQuery({
queryKey: ["todos", filter], // đổi key = query mới
queryFn: () => api.getTodos(filter),
staleTime: 60_000, // 1 phút không refetch
});
const qc = useQueryClient();
const m = useMutation({
mutationFn: api.addTodo,
onSuccess: () => qc.invalidateQueries({ queryKey: ["todos"] }),
});
- Dữ liệu stale vẫn được hiển thị ngay từ cache, đồng thời refetch nền (stale-while-revalidate) khi mount, focus lại cửa sổ, reconnect.
isPending(v5, trước làisLoading) là chưa có data;isFetchinglà đang tải bất kỳ lúc nào.- Optimistic update:
onMutatecập nhật cache,onErrorrollback.