[유데미] React Query : React로 서버 상태 관리하기
📍Prefetching 장점
- Pagination 구현 후, 유저가 다음 또는 이전 페이지를 클릭하면 fetch가 완료될때까지 Loading element를 봐야 함
- 미리 다음 페이지를 fetch하여 cache 해두면, UI가 매끄럽게 변경되어 UX를 개선할 수 있음
📍Prefetching
- cache에 data를 추가 (디폴트 : stale)
- re-fetching 시 이 data를 보여줌 (data는 cacheTime 지나면 소실)
- page 이외에도 유저가 미리 누를 가능성이 높은 탭에 미리 사용하면 좋음
📍사용 방법
1️⃣useQueryClient 를 import 한다
2️⃣useEffect 훅을 통해 currentPage가 바뀌면 prefetching을 실행하는 구조를 만든다
3️⃣nextPage 변수에 다음 페이지 번호를 할당한다
4️⃣queryClient.prefetchQuery 함수를 만들고 useQuery와 똑같이 객체를 인수로 전달한다
이 때, currentPage 대신 nextPage를 fetch하게 해주어야 한다.
5️⃣useEffect의 의존성 배열에 queryClient를 추가한다
6️⃣마지막 페이지에서는 prefetching이 필요 없으므로, if 조건문을 추가한다
const queryClient = useQueryClient();
useEffect(() => {
if (currentPage < maxPostPage) {
const nextPage = currentPage + 1;
queryClient.prefetchQuery({
queryKey: ["posts", nextPage],
queryFn: () => fetchPosts(nextPage),
});
}
}, [currentPage, queryClient]);
7️⃣이전 페이지 데이터를 캐시해두려면 본래 useQuery의 인수에 keepPreviousData를 true로 설정한다
const { data, isError, error, isLoading } = useQuery({
queryKey: ["posts", currentPage],
queryFn: () => fetchPosts(currentPage),
staleTime: 2000,
keepPreviousData: true,
});
📍isLoading vs isFetching
- 아래 코드에서 isLoading 대신 isFetching 을 사용한다면?
const { data, isError, error, isLoading } = useQuery({
queryKey: ["posts", currentPage],
queryFn: () => fetchPosts(currentPage),
staleTime: 2000,
keepPreviousData: true,
});
// 아래 조건문에서 isLoading 대신 isFetching 을 사용한다면?
if (isLoading) return <h2>Loading...</h2>;
📍isLoading
- cache data가 없음 + isFetching
📍isFetching
- 비동기 함수(promise)가 아직 resolve되지 않은 상태
- cache data가 있건 없건, stale 상태면 re-fetch 발생함
- 따라서 isLoading 대신 isFetching을 사용하면 re-fetch 전까지 짧게 Loading spinner 보여짐