Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

query-retries.md

73 lines2.2 KB

1---
2id: query-retries
3title: Query Retries
4---
5​
6When 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.
7​
8You can configure retries both on a global level and an individual query level.
9​
10- Setting `retry = false` will disable retries.
11- Setting `retry = 6` will retry failing requests 6 times before showing the final error thrown by the function.
12- Setting `retry = true` will infinitely retry failing requests.
13- Setting `retry = (failureCount, error) => ...` allows for custom logic based on why the request failed.
14​
15[//]: # 'Example'
16​
17```tsx
18import { useQuery } from '@tanstack/react-query'
19​
20// Make a specific query retry a certain number of times
21const result = useQuery({
22 queryKey: ['todos', 1],
23 queryFn: fetchTodoListPage,
24 retry: 10, // Will retry failed requests 10 times before displaying an error
25})
26```
27​
28[//]: # 'Example'
29​
30## Retry Delay
31​
32By 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.
33​
34The default `retryDelay` is set to double (starting at `1000`ms) with each attempt, but not exceed 30 seconds:
35​
36[//]: # 'Example2'
37​
38```tsx
39// Configure for all queries
40import {
41 QueryCache,
42 QueryClient,
43 QueryClientProvider,
44} from '@tanstack/react-query'
45​
46const queryClient = new QueryClient({
47 defaultOptions: {
48 queries: {
49 retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
50 },
51 },
52})
53​
54function App() {
55 return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
57```
58​
59[//]: # 'Example2'
60​
61Though 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:
62​
63[//]: # 'Example3'
64​
65```tsx
66const result = useQuery({
67 queryKey: ['todos'],
68 queryFn: fetchTodoList,
69 retryDelay: 1000, // Will always wait 1000ms to retry, regardless of how many retries
70})
71```
72​
73[//]: # 'Example3'