Query Retries

· abundance's blog


When a useQuery query fails (the query function throws an error), TanStack Query will automatically retry the query if that query's request has not reached the max number of consecutive retries (defaults to 3) or a function is provided to determine if a retry is allowed.

You can configure retries both on a global level and an individual query level.

On the server, retries default to 0 to make server rendering as fast as possible.

1import { useQuery } from '@tanstack/react-query'
2
3// Make a specific query retry a certain number of times
4const result = useQuery({
5  queryKey: ['todos', 1],
6  queryFn: fetchTodoListPage,
7  retry: 10, // Will retry failed requests 10 times before displaying an error
8})

Info: Contents of the error property will be part of failureReason response property of useQuery until the last retry attempt. So in above example any error contents will be part of failureReason property for first 9 retry attempts (Overall 10 attempts) and finally they will be part of error after last attempt if error persists after all retry attempts.

Retry Delay #

By default, retries in TanStack Query do not happen immediately after a request fails. As is standard, a back-off delay is gradually applied to each retry attempt.

The default retryDelay is set to double (starting at 1000ms) with each attempt, but not exceed 30 seconds:

 1// Configure for all queries
 2import {
 3  QueryCache,
 4  QueryClient,
 5  QueryClientProvider,
 6} from '@tanstack/react-query'
 7
 8const queryClient = new QueryClient({
 9  defaultOptions: {
10    queries: {
11      retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
12    },
13  },
14})
15
16function App() {
17  return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
18}

Though it is not recommended, you can obviously override the retryDelay function/integer in both the Provider and individual query options. If set to an integer instead of a function the delay will always be the same amount of time:

1const result = useQuery({
2  queryKey: ['todos'],
3  queryFn: fetchTodoList,
4  retryDelay: 1000, // Will always wait 1000ms to retry, regardless of how many retries
5})