Vấn đề data fetching thủ công
Fetch trong useEffect, lưu state loading/error/data, refetch khi mount hoặc khi dependency thay đổi — code lặp và dễ quên edge case. TanStack Query (React Query) đưa server state vào cache, quản lý loading/error, stale-while-revalidate, retry và invalidation.
useQuery và useMutation
useQuery nhận key và fetcher; trả về data, isLoading, error, refetch. Query key thay đổi thì fetch lại. useMutation cho POST/PUT/DELETE; sau khi success gọi queryClient.invalidateQueries để cập nhật list. Prefetch khi cần (hover link, next page).
Bình luận (0)
Đang tải bình luận...