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

query-retries.md

75 lines2.3 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> On the server, retries default to `0` to make server rendering as fast as possible.
16​
17[//]: # 'Example'
18​
19```tsx
20import { useQuery } from '@tanstack/react-query'
21​
22// Make a specific query retry a certain number of times
23const result = useQuery({
24 queryKey: ['todos', 1],
25 queryFn: fetchTodoListPage,
26 retry: 10, // Will retry failed requests 10 times before displaying an error
27})
28```
29​
30[//]: # 'Example'
31​
32## Retry Delay
33​
34By 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.
35​
36The default `retryDelay` is set to double (starting at `1000`ms) with each attempt, but not exceed 30 seconds:
37​
38[//]: # 'Example2'
39​
40```tsx
41// Configure for all queries
42import {
43 QueryCache,
44 QueryClient,
45 QueryClientProvider,
46} from '@tanstack/react-query'
47​
48const queryClient = new QueryClient({
49 defaultOptions: {
50 queries: {
51 retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
52 },
53 },
54})
55​
56function App() {
57 return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
59```
60​
61[//]: # 'Example2'
62​
63Though 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:
64​
65[//]: # 'Example3'
66​
67```tsx
68const result = useQuery({
69 queryKey: ['todos'],
70 queryFn: fetchTodoList,
71 retryDelay: 1000, // Will always wait 1000ms to retry, regardless of how many retries
72})
73```
74​
75[//]: # 'Example3'