Blog>
Snippets

Optimizing Performance with Query Prefetching

Illustrate how to prefetch data for a subsequent screen using React Query's prefetchQuery method, to enable seamless transitions and improve user experience.
import { useQueryClient } from 'react-query';
Imports the useQueryClient hook from React Query for accessing the QueryClient instance.
function prefetchNextPageData() {
  const queryClient = useQueryClient();

  // Function to prefetch data
  queryClient.prefetchQuery('nextPageData', fetchNextPageData);
}
Defines a function that uses the prefetchQuery method of the QueryClient to prefetch data for the 'nextPageData' query using the fetchNextPageData fetch function.
function NavigationButton() {
  return (
    <button onMouseEnter={prefetchNextPageData}>Go to Next Page</button>
  );
}
Renders a button component that prefetches data for the next page when the mouse enters its area, leveraging the onMouseEnter event to trigger data prefetching and thus ensuring data for the next page is loaded and cached in advance.