Blog>
Snippets

Prefetching Data for Route with React Query

Example of how to prefetch data when a user hovers over a link to another page, for instant data loading on navigate.
import { useQuery, useQueryClient } from 'react-query';
import { fetchPost } from './api';
First, import `useQuery` and `useQueryClient` from React Query, along with the `fetchPost` function from your API service.
function PostLink({ postId }) {
  const queryClient = useQueryClient();

  return (
    <div
      onMouseEnter={() => queryClient.prefetchQuery(['post', postId], () => fetchPost(postId))}
    >
      Hover over me to prefetch post data!
    </div>
  );
}
Create a component that takes `postId` as a prop. Use `onMouseEnter` on a div to prefetch data for that post. `queryClient.prefetchQuery` is used to prefetch the data, where the first argument is the query key (an array with 'post' and the postId), and the second argument is a function to fetch the data for that post.