Blog>
Snippets

Automatic Query Retry Strategy

Provides an example of setting up automatic query retries with exponential backoff strategy for failed requests using the useQuery hook options.
import { useQuery } from 'react-query';

function fetchWithRetry(url) {
  // Custom fetch function that can be used with React Query
  return fetch(url).then(async (response) => {
    if (!response.ok) throw new Error('Network response was not ok.');
    return response.json();
  });
}
This function fetchWithRetry is utilized to fetch data from a provided URL. It throws an error if the fetched response is not okay, which triggers the retry in case of failure.
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: 3, // Number of retries
      retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000), // Exponential backoff
    },
  },
});
Setting up the QueryClient with default options for automatic retries. A maximum of 3 retries will be attempted with an exponential backoff strategy for the delay between retries, capped at 30 seconds.
function useData() {
  return useQuery(['dataKey'], () => fetchWithRetry('/data-endpoint'), {
    retry: 2, // Overrides the default if needed
    retryDelay: attemptIndex => 1000 * 2 ** attemptIndex, // Custom retry delay for this query
  });
}
The useData hook uses the useQuery hook from React Query to fetch data from '/data-endpoint' using the fetchWithRetry function. It specifies a custom retry strategy for this specific query, different from the default set in QueryClient, if needed.