Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 38 ยท Caching and Staleness

Retries and Error Handling

Handle failures well: default retries and back-off, custom retry rules, global error callbacks with QueryCache, throwOnError, network modes and refetch errors that keep old data.

Networks fail. Servers return 500s, laptops go through tunnels, a user's Wi-Fi drops for two seconds. Good data-fetching code survives the short failures quietly and reports the lasting ones clearly. TanStack Query gives you automatic retries, a back-off schedule, several places to react to errors, and a clear model for what happens to the data you already have when a refetch fails.

Automatic retries

When a queryFn rejects, Query does not fail immediately. By default it retries 3 times with exponential back-off (1 s, 2 s, 4 s, capped at 30 s), and only after that puts the query in the error state. During the retries, status stays pending (or success if you have old data), and failureCount and failureReason tell you what has happened so far.

JSX
useQuery({
  queryKey: ["todos"],
  queryFn: fetchTodos,
  retry: 5,                                              // number of retries
  retryDelay: (attempt) => Math.min(1000 * 2 ** attempt, 10000),
});

retry can be:

  • a number (0 disables retries),
  • true (retry forever) or false,
  • a function (failureCount, error) => boolean, to decide per error.

Mutations default to retry: 0, as explained in Mutations with useMutation.

Retry only what can recover

Retrying a 404 (not found) or 401 (not logged in) three times just wastes time; the answer will not change. A retry function lets you separate temporary from permanent failures:

A smart retry function

The flaky server recovers on the third attempt, the broken one is retried three times and then reported, and the 404 stops after a single attempt because the function returned false.

What happens to existing data when a refetch fails

Suppose a list is loaded, and a background refetch then fails. Query keeps the old data; it only adds the error information:

State data isError isRefetchError
First fetch failed undefined true false
Refetch failed, old data exists old data true true

A failed background refetch sets status: "error" but leaves data in place. Components that check isError first will therefore replace a perfectly good list with an error message. Prefer to show data when you have it, and add the error as a banner:

JSX
if (isPending) return <Spinner />;
if (data) {
  return (
    <>
      {isRefetchError && <Banner>Could not refresh. Showing older data.</Banner>}
      <List items={data} />
    </>
  );
}
return <ErrorScreen error={error} />;

Where to handle errors

There are four places, from local to global:

  1. In the component: read error and isError from the hook (as above).
  2. Per call with a callback on the mutation: onError (see Mutation Callbacks).
  3. Globally for queries, with the QueryCache. In v5, useQuery no longer has onError/onSuccess callbacks, because they ran once per observer and led to duplicate toasts. The cache callback runs once per failed query:
JavaScript
import { QueryCache, QueryClient } from "@tanstack/react-query";

const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: (error, query) => {
      // show a toast only if the query had data (a background failure)
      if (query.state.data !== undefined) showToast("Refresh failed: " + error.message);
    },
  }),
});
  1. In an error boundary, by letting the error propagate to React (next section).

throwOnError and error boundaries

Setting throwOnError: true makes a failed query throw during render, so the nearest React error boundary catches it. This is the natural fit for Suspense, where useSuspenseQuery throws by default. You can also pass a function to choose which errors escalate:

JSX
useQuery({
  queryKey: ["profile"],
  queryFn: fetchProfile,
  throwOnError: (error) => error.status >= 500,   // only server errors go to the boundary
});

The boundary shows a fallback, and QueryErrorResetBoundary lets the "Try again" button clear the error state so the query can retry. Error Boundaries and Resetting covers the full pattern.

Typing errors

The error is unknown in practice, because anything can be thrown. In TypeScript, v5 types it as Error by default, and you can register your own type once, globally, so that every error is an HttpError | Error. In JavaScript, check with instanceof or a custom field such as status, as the demo did.

Network modes

networkMode decides what Query does when the device is offline:

Mode Behavior
"online" (default) Queries pause while offline and resume when the network returns. No failure, no retry burn.
"always" Ignore the online state and always try, which suits local servers and mocked APIs.
"offlineFirst" Run the first attempt even offline (for a service worker or HTTP cache to answer), then pause retries.

A paused query has fetchStatus: "paused", the same flag shown in Query Status and Fetch Status. If a request needs local services in development and the app seems "stuck loading", the browser may be reporting offline; try "always" there.

A short checklist

  • Leave the default retries for flaky public networks, and use retry: false in tests (see Testing Queries and Mutations).
  • Do not retry 4xx errors.
  • Keep showing old data on a failed refresh.
  • Report background failures once, through the QueryCache.
  • Escalate only what the user must see to an error boundary.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the default retry settings for queries?

    Queries retry 3 times, waiting 1 s, 2 s, 4 s and so on, capped at 30 s.
  2. 2. Which retry function avoids pointless retries of client errors?

    Return false for 4xx statuses and cap the others, so only recoverable failures are retried.
  3. 3. A background refetch fails while old data is on screen. What does v5 do with data?

    The old data stays; error and isRefetchError tell you the refresh failed.
  4. 4. Where should you put a global toast for failed queries in v5?

    useQuery callbacks were removed in v5. QueryCache callbacks run once per query instead of once per observer.

Summary

  • Queries retry 3 times with exponential back-off; mutations do not retry unless configured.
  • Use a retry function to skip errors that cannot recover, such as 4xx statuses.
  • A failed refetch keeps the old data; render data first and show errors as a banner.
  • Global error reporting belongs in QueryCache/MutationCache callbacks; throwOnError sends errors to boundaries.
  • networkMode controls offline behavior; paused queries resume on reconnect.

Next: Working with the Cache Directly