Prefetch Data with React Query to Skip Loading States on Navigation
Use React Query's prefetch capabilities in navigation listeners to load data before a screen mounts, eliminating loading spinners and improving perceived performance.
Insight
When a user navigates to a new screen, the UI often shows a loading spinner while the data fetch resolves. In React Native, this can feel sluggish, especially on slower networks. React Query lets you prefetch data before the component mounts by calling queryClient.prefetchQuery in a navigation listener. The next screen can then read the cached result instantly, turning a potential wait into a seamless transition.
Example
import { useEffect } from 'react';
import { useNavigation, NavigationProp } from '@react-navigation/native';
import { useQueryClient } from '@tanstack/react-query';
import { fetchUserProfile } from '../api/user';
export function usePrefetchUser(userId: string) {
const navigation = useNavigation<NavigationProp<any>>();
const queryClient = useQueryClient();
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// Prefetch the profile so the next screen reads it instantly
queryClient.prefetchQuery(['user', userId], () => fetchUserProfile(userId));
});
return unsubscribe;
}, [navigation, queryClient, userId]);
}
In the target screen you can simply call useQuery(['user', id], ...) – the data will already be in the cache and the UI renders immediately.
Takeaway
Hook into navigation events to prefetch critical queries. By warming the cache ahead of time you remove the visual loading gap, delivering a faster, more fluid user experience without extra boilerplate.