Sub topic 7
Automatic refetching and retries
This chapter assumes you know useQuery, query keys, and how staleTime and gcTime decide whether cached data is fresh. Here you learn what makes TanStack Query (React Query v5) fetch again without your code asking, and what it does when a fetch fails.
Why refetching is automatic
A cached value starts to age as soon as the server sends it. The library handles this with a rule: when something that suggests the data may have changed happens, check any stale data that someone is displaying. You don't write the useEffect that does it.
The rule has two parts. A trigger is an event such as a component mounting or the browser tab regaining focus. A staleness check then decides whether that trigger leads to a request. With the default staleTime of 0, data is stale the moment it arrives, so every trigger refetches.
The built-in triggers
| Trigger | Option | Default |
|---|---|---|
| A new component using the query mounts | `refetchOnMount` | `true` |
| The browser window regains focus | `refetchOnWindowFocus` | `true` |
| The network connection comes back | `refetchOnReconnect` | `true` |
| A timer elapses | `refetchInterval` | `false` (off) |
Each of the first three accepts true, false, or 'always'. true refetches only if the data is stale. false never refetches on that trigger. 'always' refetches even when the data is fresh.
Triggers only affect active queries, meaning queries with at least one mounted component observing them. An inactive query waits in the cache until it is used again or garbage collected after gcTime.
Window focus and why it surprises people
Window focus refetching is the trigger most often mistaken for a bug. A developer clicks from the editor to the browser, sees a request in the network tab, and wonders why. The cause is staleTime: 0 combined with refetchOnWindowFocus: true.
Raising staleTime fixes this for most data. Turning the option off should be a deliberate choice, for example for a form that loads server data and must not change while the user types:
import { useQuery } from '@tanstack/react-query'
type Settings = { theme: string; language: string }
async function fetchSettings(): Promise<Settings> {
const res = await fetch('/api/settings')
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
export function SettingsForm() {
const { data, isFetching } = useQuery({
queryKey: ['settings'],
queryFn: fetchSettings,
staleTime: 5 * 60 * 1000,
refetchOnWindowFocus: false,
})
return (
<form>
<input defaultValue={data?.theme} />
{isFetching && <span>Refreshing...</span>}
</form>
)
}isFetching is true during any request, including background refetches. isPending is true only when there is no data yet. Use isFetching for a small refresh indicator and isPending for the full loading state.
Polling with refetchInterval
refetchInterval takes a number of milliseconds and refetches on that schedule. It ignores staleness: a poll always fetches. By default polling pauses while the tab is hidden. Set refetchIntervalInBackground: true if it must continue.
In v5, refetchInterval can also be a function that receives the query. This lets you stop polling once the work is finished:
import { useQuery } from '@tanstack/react-query'
type Job = { id: number; status: 'queued' | 'running' | 'done' }
async function fetchJob(id: number): Promise<Job> {
const res = await fetch(`/api/jobs/${id}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
export function JobStatus({ id }: { id: number }) {
const { data } = useQuery({
queryKey: ['jobs', id],
queryFn: () => fetchJob(id),
refetchInterval: (query) =>
query.state.data?.status === 'done' ? false : 2000,
})
return <p>Status: {data?.status ?? 'loading'}</p>
}Returning false turns polling off for that query. If the job later restarts, the function runs again after the next fetch, so polling resumes as needed.
Retries
When a queryFn throws or returns a rejected Promise, the library does not fail immediately. It retries.
- In the browser, a failed query is retried 3 times by default.
- The delay between attempts grows exponentially:
Math.min(1000 * 2 ** attemptIndex, 30000)milliseconds. That gives 1 second, 2 seconds, 4 seconds, and so on, capped at 30 seconds. - While retries run, the query stays in its
pendingstatus. Only after the last retry fails does it becomeerror. - On the server, such as during server rendering, the default is
0retries.
During this period failureCount and failureReason on the query result show how many attempts have failed and the most recent error.
A consequence for UI: if the API is down, the user sees the loading state for about 7 seconds (1 + 2 + 4) before your error message appears. That is often longer than intended.
The retry option accepts a number, true (retry forever), false (no retries), or a function. The function receives the number of failures so far, starting at 0 for the first failure, and the error. It returns true to retry again. Retrying a 404 or a 403 is pointless because the same request will get the same answer, so a function is the usual choice. Set it once for the whole app:
import { QueryClient } from '@tanstack/react-query'
export class HttpError extends Error {
status: number
constructor(status: number) {
super(`Request failed: ${status}`)
this.status = status
}
}
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 30 * 1000,
retry: (failureCount, error) => {
if (
error instanceof HttpError &&
error.status >= 400 &&
error.status < 500
) {
return false
}
return failureCount < 3
},
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
},
},
})For this to work, your queryFn must throw an HttpError (or another error carrying the status) when res.ok is false. The library cannot see HTTP status codes itself, only thrown errors. Options set on an individual useQuery call override these defaults.
Offline behavior
The default networkMode is 'online'. If the browser reports no connection, the library does not start the fetch and does not count it as a failure. The query keeps its fetchStatus as 'paused' and resumes when the connection returns. Check fetchStatus if you want to show an "offline" banner, since status alone will still read pending.
Mutations do not retry by default
useMutation defaults to retry: 0. A retried POST could create a duplicate record, so retrying is opt-in. Enable it only for operations that are safe to repeat (idempotent), such as a PUT that sets a value.
Common problems
- Too many requests. Cause:
staleTime: 0with focus, mount, and reconnect triggers. Fix: set a realisticstaleTimeindefaultOptions. - Errors take seconds to appear. Cause: three retries with backoff. Fix: lower
retryor skip retries for client errors. - Retries never happen. Cause:
queryFnswallowed the failure, for example by not checkingres.ok.fetchonly rejects on network failure, so a500response looks like success unless you throw. - Tests hang or time out on error cases. Cause: default retries and backoff. Fix: set
retry: falsein the testQueryClient. - Polling continues forever. Cause: constant
refetchInterval. Fix: use the function form and returnfalse.
Exercise
A query uses staleTime: 60000 and the default refetchOnWindowFocus. The user fetched the data 20 seconds ago, switches to another tab, and comes back. Does a request go out? What would change if refetchOnWindowFocus were 'always', and what if the endpoint returns a 500 on the next attempt?
Show answer
No request goes out. With refetchOnWindowFocus: true, the library refetches only stale data, and data fetched 20 seconds ago is still fresh under a 60-second staleTime. With 'always', the focus event refetches even though the data is fresh. If a refetch gets a 500 and the queryFn throws, the library retries up to 3 times with delays of 1, 2, and 4 seconds. The existing cached data stays on screen during this time, and failureCount increases with each failed attempt. If every retry fails, the query moves to the error status while data still holds the last good value.