Blog>
Snippets

Implementing Prefetching for Anticipated Data

Provide an example of how to use React Query's prefetching feature to load data that the user is likely to request soon, thereby improving the perceived performance of the application.
import { QueryClient, useQueryClient } from 'react-query';
import axios from 'axios';

// Function to fetch posts
const fetchPosts = async () => {
  const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
  return data;
};
This code imports necessary dependencies and defines a fetchPosts function using axios to get data from a placeholder API.
const queryClient = new QueryClient();
Creates a new instance of QueryClient which allows us to utilize React Query's features such as caching and prefetching.
queryClient.prefetchQuery('posts', fetchPosts);
This line tells React Query to prefetch the 'posts' data by calling the fetchPosts function. This prefetching occurs as soon as the code runs, loading the data before the user explicitly requests it.
const PostsComponent = () => {
  const queryClient = useQueryClient();
  const { data: posts, isLoading } = useQuery('posts', fetchPosts);

  // Prefetch individual post on hover
  const prefetchPost = async (postId) => {
    await queryClient.prefetchQuery(['post', postId], () => fetchPost(postId));
  };

  if (isLoading) return <div>Loading...</div>;

  return (
    <ul>
      {posts.map(post => (
        <li key={post.id} onMouseEnter={() => prefetchPost(post.id)}>
          {post.title}
        </li>
      ))}
    </ul>
  );
};
This PostsComponent uses the useQuery hook to load and display a list of posts. It also features a prefetchPost function, called on mouse enter, to prefetch individual post data using queryClient.prefetchQuery, demonstrating a practical use of prefetching to improve user experience.