Transient network recovery
A flaky network request should recover without immediately displaying an error.
TanStack · Pipe
The retry option controls whether failed TanStack Query requests run again. It supports a retry count, disabling or infinite retries, and a callback for error-aware decisions.
The retry option controls whether a failed query runs again. It accepts a retry count, false to disable retries, true for unlimited retries, or a function that decides from the failure count and error; client defaults are three retries, while server defaults are zero.
retry: number | false | true | ((failureCount: number, error: TError) => boolean)| Name | Type | Description |
|---|---|---|
retry | number | false | true | ((failureCount: number, error: TError) => boolean) | Maximum retry count, false to disable retries, true for infinite retries, or a predicate receiving failureCount and error. |
import { useQuery } from '@tanstack/react-query'
export function Todos() {
const query = useQuery({
queryKey: ['todos'],
queryFn: async () => {
const response = await fetch('/api/todos')
if (!response.ok) throw new Error('Request failed')
return response.json()
},
retry: (failureCount, error) => {
if (error instanceof Error && error.message === 'Request failed') {
return failureCount < 2
}
return false
},
})
return <pre>{JSON.stringify(query.data ?? null)}</pre>
}The query retries only twice for this error, then exposes the final failure.
A flaky network request should recover without immediately displaying an error.
Only selected errors should be retried while permanent failures stop immediately.
Different environments need different latency and resilience trade-offs.
retry may be false, true, a number, or a function receiving failureCount and error. false prevents retries, true retries indefinitely, a number limits retries, and the function returns whether another attempt is allowed.
Follow-up: How would you avoid retrying authentication failures? Return false from the function when the error represents an authentication failure, and retry only transient failures.
The client default is three retries, but server rendering defaults to zero. This avoids making server-side rendering wait through retry attempts unless the application explicitly opts in.
Follow-up: Why might a server application configure retries explicitly? It may need resilience for transient upstream failures, while accepting the added rendering latency.
The retry callback receives the current failureCount and the thrown error. Because the first retry attempt has a count of zero, a condition such as failureCount < 2 permits two retry attempts.
Follow-up: How can retry timing be customized? Configure retryDelay with a number or function; a function can implement linear or exponential backoff.
retryDelayuseQueryQueryClientQueryOptions