Blog>
Snippets

Conditional Data Prefetching Based on Network Status

Illustrate how to conditionally prefetch data with React Query based on the user's network status. The example will use the Navigator API to check if the user has a slow connection and conditionally skip prefetching to conserve bandwidth.
import { useQuery } from 'react-query';
import { fetchProductDetails } from './api';

function prefetchProductDetails(productId) {
  // Use Navigator API to check network connection type
  if (navigator.connection) {
    const { effectiveType } = navigator.connection;

    // Skip prefetching if the user is on a slow connection
    if (effectiveType.includes('2g')) {
      console.log('Skipping prefetch due to slow connection');
      return;
    }
  }

  // Prefetch the product details
  return useQuery(['product', productId], () => fetchProductDetails(productId), {
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}
This code checks the user's network status using the Navigator API before prefetching product details with React Query. If the connection is slow (e.g., '2g'), prefetching is skipped to conserve bandwidth. Otherwise, the product details are prefetched and cached with a stale time of 5 minutes, enhancing the user experience under better network conditions.