Optimizing Prefetching Strategies

Illustrate how to prefetch data with React Query, showcasing how to anticipate user actions and load data before it's requested for an improved user experience.
import { useQuery } from 'react-query';

// Define a function to fetch data
const fetchData = async () => {
  const response = await fetch('');
  if (!response.ok) throw new Error('Network response was not ok');
  return response.json();
First, import useQuery from react-query and define a fetchData function that fetches data from an API.
const HomePage = () => {
  // Prefetch data on component mount
  useQuery('data', fetchData, { staleTime: Infinity, cacheTime: 0 });

  return (
      <h1>Home Page</h1>
      {/* Render your components here */}
In your HomePage component, use useQuery to prefetch data when the component mounts. Use 'staleTime: Infinity' to keep the data fresh indefinitely and 'cacheTime: 0' to not cache the data, anticipating that it will be used immediately.
import { useQueryClient } from 'react-query';

const UserProfile = () => {
  const queryClient = useQueryClient();

  // Function to prefetch user data on hover
  const maybeFetchUserData = () => {
    queryClient.prefetchQuery('userData', fetchUserData, {
      staleTime: 1000 * 60 * 10, // 10 minutes

  return (
    <button onMouseEnter={maybeFetchUserData}>Load User Profile</button>
In the UserProfile component, use useQueryClient to access the queryClient. Define a maybeFetchUserData function that prefetches data on mouse hover. Use queryClient.prefetchQuery with a specific key and the fetchUserData function, setting a staleTime to control freshness.