Blog>
Snippets

React Query Prefetching on Route Hover

Demonstrate how to prefetch data when a user hovers over a link using React Router and React Query. This involves setting up an onMouseEnter event on the link component that triggers the prefetching process.
import { prefetchQuery } from '@tanstack/react-query';
First, import the prefetchQuery method from React Query.
import { fetchProduct } from './api';
Import the async function 'fetchProduct' that fetches data from an API.
import { Link } from 'react-router-dom';
Import Link from React Router dom for navigation.
function ProductLink({ productId }) {
  return (
    <Link
      to={`/products/${productId}`}
      onMouseEnter={() => {
        // Prefetch the product data on hover
        prefetchQuery(['product', productId], () => fetchProduct(productId));
      }}
    >
      View Product
    </Link>
  );
}
Create a 'ProductLink' component. Use the onMouseEnter event on the link to trigger data prefetching for the product details. The prefetchQuery function takes a unique key ['product', productId] and a query function as arguments. This ensures the product data is fetched and cached before the user navigates to the product page, resulting in a faster user experience.