Blog>
Snippets

Prefetching Data for Next Route with React Query

Showcase how to use React Query's 'prefetchQuery' method to prefetch data for an anticipated navigation route when a user hovers over a link.
import { useQueryClient } from 'react-query';
Import useQueryClient from react-query to access the QueryClient instance.
function prefetchPostData(postId) {
  const queryClient = useQueryClient();

  // Prefetch the post data when the user hovers over the link
  queryClient.prefetchQuery(['post', postId], () => fetchPostById(postId));
}
Define a function to prefetch data for a post using the postId. The 'prefetchQuery' method is used to fetch the data ahead of when it's needed and cache it.
<a onMouseEnter={() => prefetchPostData(post.id)} href={`/post/${post.id}`}>Go to Post</a>
Trigger the prefetching of post data by attaching the onMouseEnter event to a link. When the user hovers over the link, the prefetchPostData function is called.