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

query-retries.md

53 lines2.0 KB

1---
2id: query-retries
3title: Query Retries
4---
5​
6When a `useQuery` query fails (the query function throws an error), React 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```js
16import { useQuery } from 'react-query'
17​
18// Make a specific query retry a certain number of times
19const result = useQuery(['todos', 1], fetchTodoListPage, {
20 retry: 10, // Will retry failed requests 10 times before displaying an error
21})
22```
23​
24## Retry Delay
25​
26By default, retries in React Query do not happen immediately after a request fails. As is standard, a back-off delay is gradually applied to each retry attempt.
27​
28The default `retryDelay` is set to double (starting at `1000`ms) with each attempt, but not exceed 30 seconds:
29​
30```js
31// Configure for all queries
32import { QueryCache, QueryClient, QueryClientProvider } from 'react-query'
33​
34const queryClient = new QueryClient({
35 defaultOptions: {
36 queries: {
37 retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
38 },
39 },
40})
41​
42function App() {
43 return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
45```
46​
47Though 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:
48​
49```js
50const result = useQuery('todos', fetchTodoList, {
51 retryDelay: 1000, // Will always wait 1000ms to retry, regardless of how many retries
52})
53```