How to prefetch queries in React Query
Prefetching queries in React Query loads data in advance before users navigate to a page or trigger an action, creating a seamless experience with instant data display. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented prefetching strategies in data-heavy admin dashboards throughout my 11 years of React development. The most effective approach is using queryClient.prefetchQuery in event handlers or navigation logic to load data proactively. This method populates the cache before components mount, eliminating loading states for better user experience.
Use queryClient.prefetchQuery to load data in advance before components need it.
import { useQueryClient } from '@tanstack/react-query'
const fetchUserDetails = async (userId) => {
const response = await fetch(`/api/users/${userId}`)
if (!response.ok) throw new Error('Failed to fetch user')
return response.json()
}
const UserList = () => {
const queryClient = useQueryClient()
const handleMouseEnter = (userId) => {
queryClient.prefetchQuery({
queryKey: ['user', userId],
queryFn: () => fetchUserDetails(userId),
staleTime: 10000
})
}
return (
<ul>
{users.map(user => (
<li
key={user.id}
onMouseEnter={() => handleMouseEnter(user.id)}
>
<Link to={`/users/${user.id}`}>{user.name}</Link>
</li>
))}
</ul>
)
}
Here queryClient.prefetchQuery executes when users hover over a user link, fetching user details before navigation occurs. The prefetched data stores in the React Query cache with the same queryKey that the detail page will use. When users click the link and navigate to the user detail page, the data already exists in cache, displaying instantly without loading spinners. The staleTime option keeps prefetched data fresh for 10 seconds, preventing unnecessary refetches if users navigate quickly.
Best Practice Note:
This is the prefetching pattern we use in CoreUI admin templates for instant navigation between list and detail views. Prefetch on hover or focus events for likely navigation targets, set appropriate staleTime to balance freshness and performance, and avoid prefetching too aggressively to prevent unnecessary network requests and bandwidth usage.



