Optimizing Performance through Query Prefetching on Route Hover
Provide an example of how to prefetch data using React Query's prefetchQuery function when a user hovers over a link, reducing load time when they navigate to the page.
import { prefetchQuery } from '@tanstack/react-query';
Import prefetchQuery function from React Query.
import { fetchUserData } from './api/user';
Import a mock function that simulates fetching user data from an API.
function prefetchUser(userId) {
prefetchQuery(['user', userId], () => fetchUserData(userId));
}
Defines a function to prefetch user data using React Query's prefetchQuery by providing a unique key and the fetch function.
<a onMouseEnter={() => prefetchUser(1)} href="/user/1">Go to User 1's profile</a>
An anchor tag that prefetches user data when the mouse enters its area, reducing load time when the user navigates to this route.