~/swaraj.dev
Back to all posts
March 25, 20261 min read

Prefetch Data with React Query for Seamless Screen Transitions

Use React Query's prefetch capabilities to load data before a user navigates, eliminating loading spinners and improving perceived performance.

react queryperformancereact native

Insight

When navigating between screens, fetching data only after the new screen mounts often results in a noticeable loading state. React Query lets you prefetch data in the background while the user is still on the current screen. By tying a prefetch to a navigation event (e.g., onPress or focus), the next screen can render instantly with data already in the cache, delivering a smoother experience.

Example

import { useNavigation } from '@react-navigation/native';
import { useQueryClient } from '@tanstack/react-query';
import { TouchableOpacity, Text } from 'react-native';

const ItemCard = ({ id }: { id: string }) => {
  const navigation = useNavigation();
  const queryClient = useQueryClient();

  const handlePress = () => {
    // Warm the cache before navigation
    queryClient.prefetchQuery(['item', id], () => fetchItem(id));
    navigation.navigate('ItemDetail', { id });
  };

  return (
    <TouchableOpacity onPress={handlePress}>
      <Text>Open Item {id}</Text>
    </TouchableOpacity>
  );
};

Takeaway

Trigger queryClient.prefetchQuery right before navigation. The target screen can then call useQuery(['item', id]) and instantly receive cached data, eliminating loading spinners and boosting perceived performance.