aotoyae

[React] TanStack Query : Prefetching 프리패칭 본문

React

[React] TanStack Query : Prefetching 프리패칭

aotoyae 2024. 8. 7. 01:15

 

 

💡 UX 를 개선하기 위해 데이터를 미리 가져오는 기능

 

페이지 이동 전, 이동할 페이지의 쿼리를 미리 호출(prefetching)!

캐시 데이터가 있는 상태로 다음 페이지로 이동 시 로딩 없이 바로 UI 가 나타난다.

 

Header.jsx

const onMouseOver = () => { // 메뉴에 마우스가 올라오면 호출
    if (pathname !== "/") return;

    queryClient.prefetchQuery({
      queryKey: ["movies", 1], // 1 페이지 데이터 요청
      queryFn: fetchMovieData,
    });
  };

 

메뉴에 마우스가 올라오면 데이터를 미리 불러놓는다.

 

MoviePagination.jsx

const { data: movies, isLoading } = useQuery({
    queryKey: ["movies", page], // initial queryKey:["movie", 1]
    queryFn: fetchMovieData,
    select: ({ total_pages, results }) => ({
      total_pages,
      results,
    }),
    keepPreviousData: true,
  });

 

 

 

🔗 https://tanstack.com/query/latest/docs/framework/react/guides/prefetching