Blog>
Snippets

Optimizing Prefetching with React Query

Detail how to prefetch data for upcoming navigation actions using React Query's prefetchQuery method to enhance user experience by reducing loading times.
import { useQueryClient } from 'react-query';
First, import useQueryClient from React Query to get access to the QueryClient instance, which allows you to interact with the cache and other utilities.
const queryClient = useQueryClient();
Inside your component or function, instantiate the queryClient using the useQueryClient hook. This queryClient instance provides methods to prefetch data.
const prefetchProduct = async (productId) => {
  await queryClient.prefetchQuery(['product', productId], () => 
    fetch(`https://api.example.com/products/${productId}`).then(res => res.json())
  );
};
Define a function to prefetch data for an upcoming navigation action. Here, prefetchQuery is used to prefetch the product data based on a productId. The first argument is the query key (an array where the first element is a string identifying the query and the second element is a dynamic value), and the second argument is an asynchronous function that fetches the data.
prefetchProduct('123');
Call the prefetching function with a specific productId ('123' in this example) when it's likely the user will navigate to this product's page soon. This preemptively fetches and caches the data, making the eventual transition to the product detail page appear almost instantaneous to the user.