Blog>
Snippets

Automatic Query Retries with Exponential Backoff

Configuring a query to automatically retry with exponential backoff strategy in case of failure.
import { useQuery } from 'react-query';

function fetchWithRetry(url) {
  // Function to fetch data, will be passed to react-query's useQuery
  return fetch(url).then(async (res) => {
    if (!res.ok) throw new Error('Network response was not ok.');
    return res.json();
  });
}
Defines a function 'fetchWithRetry' to fetch data from a URL. This function will automatically throw an error if the response is not successful, which triggers the retry mechanism in React Query.
const { data, status } = useQuery(
  'uniqueKeyForQuery',
  () => fetchWithRetry('https://example.com/data'),
  {
    retry: 3, // Number of retries
    retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000), // Exponential backoff strategy
  }
);
Uses the 'useQuery' hook from React Query to fetch data with an automatic retry mechanism. The 'retry' property specifies the maximum number of retries, and 'retryDelay' calculates the delay before each retry attempt, using an exponential backoff strategy.