Sub topic 7
Automatic refetching and retries
This chapter assumes you can write a useQuery call and know how staleTime decides whether cached data is fresh or stale. Here you will see what makes a query fetch again without any code of yours, and what happens when a fetch fails.
When queries refetch on their own
A query refetches automatically when one of these events happens and the data is stale:
| Trigger | Option | Default |
|---|---|---|
| A component using the query mounts | `refetchOnMount` | `true` |
| The browser window regains focus | `refetchOnWindowFocus` | `true` |
| The network connection returns | `refetchOnReconnect` | `true` |
| A timer fires | `refetchInterval` | off |
With the default staleTime of 0, data is stale as soon as it arrives. That is why a query seems to refetch every time you switch tabs. Raising staleTime is usually the right fix, because fresh data is never refetched by the first three triggers.
refetchInterval is different. It polls on a timer whether or not the data is stale. By default polling pauses while the tab is in the background. Set refetchIntervalInBackground: true to keep it running.
The three event options also accept 'always', which refetches even when the data is fresh, or false, which turns the trigger off.
Retries
If a queryFn throws, the query does not fail at once. In the browser it retries up to 3 times, with exponential backoff between attempts. The default delay is Math.min(1000 * 2 ** attemptIndex, 30000) milliseconds, so about 1s, 2s, then 4s. During retries the query stays in pending status (or keeps its old data) while failureCount rises. isError becomes true only after the last retry fails.
This is why your queryFn must throw on a bad HTTP status. A fetch that resolves with a 500 response counts as success unless you check res.ok and throw.
Retrying a 404 or 403 wastes time, because the result will not change. Pass a function to retry to decide per error:
import { useQuery } from '@tanstack/react-query'
type Todo = { id: number; title: string; done: boolean }
class HttpError extends Error {
status: number
constructor(status: number) {
super(`Request failed: ${status}`)
this.status = status
}
}
async function fetchTodos(): Promise<Todo[]> {
const res = await fetch('/api/todos')
if (!res.ok) throw new HttpError(res.status)
return res.json()
}
export function Todos() {
const { data, isError, isFetching } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
staleTime: 30 * 1000,
refetchInterval: 60 * 1000,
retry: (failureCount, error) => {
const clientError =
error instanceof HttpError && error.status >= 400 && error.status < 500
return !clientError && failureCount < 3
},
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
})
if (isError) return <p>Could not load todos.</p>
return (
<div>
{isFetching && <small>Updating...</small>}
<ul>
{data?.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
</div>
)
}Common mistakes
- Seeing "too many requests" and blaming the library. Check the
staleTimefirst. - Tests that hang on failing queries. The default retries and backoff delay the error, so set
retry: falsein test clients. - Polling a rarely changing endpoint. A longer
staleTimeplus invalidation after mutations is cheaper.
Exercise
A query has staleTime: 5 * 60 * 1000 and no refetchInterval. A user switches to another tab and back after 2 minutes. Does the query refetch? What if you add refetchInterval: 30000?
Show answer
Without the interval, it does not refetch. The data is still fresh (2 minutes is under 5), so the window focus trigger is skipped. With refetchInterval: 30000, the query refetches every 30 seconds regardless of staleness. It pauses while the tab is in the background unless refetchIntervalInBackground is true.