비동기 요청은 받아오는 속도가 느리고, 데이터 양이 방대할수록 오래걸린다.
사용자 경험을 위해 데이터를 미리 받아 캐싱해놓으면, 새로운 데이터를 받기 전에 사용자가 캐싱된 데이터를 볼 수 있어 UX에 큰 영향을 끼친다.
useEffect
를 사용해 현재 페이지의 상태가 바뀔 때마다 의존성에 의해 다음 페이지의 데이터를 요청하는 방법을 쓴다.import { useEffect, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
async function fetchPosts(pageId) {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?_limit=10&_page=${pageId}`
);
return response.json();
}
const queryClient = useQueryClient();
useEffect(() => {
if (currentPage < maxPostPage) {
const nextPage = currentPage + 1;
queryClient.prefetchQuery(["posts", nextPage], () =>
fetchPosts(nextPage)
);
}
}, [currentPage, queryClient]);
const { data, isLoading, isError } = useQuery(
["posts", currentPage],
() => fetchPosts(currentPage),
{ staleTime: 2000, keepPreviousData: true }
);
isFetching
isFetching
은 비동기 함수가 아직 데이터를 가져오지 못했을 때, true를 반환한다.isLoading
isLoading
은 비동기 함수를 가져오지 못했으며, 캐싱된 데이터도 존재하지 않을 때, true를 반환한다.