Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 38 ยท Suspense and Prefetching

Error Boundaries and Resetting

Handle query errors with React error boundaries: throwOnError, QueryErrorResetBoundary, useQueryErrorResetBoundary, retry buttons and a clean split of local and global errors.

Suspense handles the "waiting" state. Its twin for failures is the error boundary: a React component that catches errors thrown while rendering its children and shows a fallback instead of crashing the whole tree. Together, they let a component contain only the happy path.

TanStack Query connects to error boundaries in two ways. Suspense hooks throw errors automatically, and regular useQuery throws when you set throwOnError. This lesson shows how to catch those errors, how to let the user retry correctly, and how to decide which errors deserve a boundary at all.

Why a plain boundary is not enough

An error boundary stays in its error state until it is reset. If the user clicks "Try again" and the boundary re-renders its children, the query inside them sees... the same failed query in the cache. By default a failed query that has errored will not retry just because it re-mounts, and a suspense query would throw the cached error again right away. You must tell the query to reset, as well as the boundary.

QueryErrorResetBoundary does both jobs: it tracks the queries that threw below it, and when you call its reset(), those queries are reset, so the next render starts a fresh request.

JSX
import { QueryErrorResetBoundary } from "@tanstack/react-query";
import { ErrorBoundary } from "react-error-boundary";   // a small library, or write your own

<QueryErrorResetBoundary>
  {({ reset }) => (
    <ErrorBoundary
      onReset={reset}
      fallbackRender={({ resetErrorBoundary, error }) => (
        <div>
          <p>Could not load: {error.message}</p>
          <button onClick={resetErrorBoundary}>Try again</button>
        </div>
      )}
    >
      <Suspense fallback={<p>Loading...</p>}>
        <Profile />
      </Suspense>
    </ErrorBoundary>
  )}
</QueryErrorResetBoundary>

Clicking Try again calls resetErrorBoundary, which calls onReset (the query reset), which re-renders the children, which fetch again. The order of nesting matters: the error boundary sits outside Suspense, since an error boundary must catch what the suspended child throws.

A runnable boundary

The page cannot load react-error-boundary, so the example uses a minimal hand-written class component. It is about ten lines and is all you need.

QueryErrorResetBoundary with a retry button

Two attempts fail and show the error with a button; the third succeeds. Because the reset also clears the query's error state, each click really issues a new request. retry: false was added only so the demo fails fast; in a real app the default retries (three tries with growing delays) handle most flaky networks before any boundary appears.

useQuery and throwOnError

With useQuery you opt in to throwing:

JavaScript
useQuery({
  queryKey: ["profile"],
  queryFn: fetchProfile,
  throwOnError: true,                           // always throw to the boundary
})

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

The function form is the practical one: a 404 ("this user does not exist") is better handled in the component, where you can render a friendly "not found" page, while a 500 means something is broken and belongs in a boundary. For a useSuspenseQuery, throwing is built in.

Rule of thumb: expected errors stay local, unexpected errors go to boundaries.

Global handling with QueryCache

For things that apply to every query, such as showing a toast or logging to a monitoring tool, set callbacks on the cache once instead of repeating onError everywhere. In v5 the per-query onError callbacks were removed from useQuery, so the cache is the supported place:

JavaScript
import { QueryCache, QueryClient } from "@tanstack/react-query";

const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: (error, query) => {
      if (query.state.data !== undefined) {
        toast.error("Background refresh failed: " + error.message);
      }
    },
  }),
});

The check query.state.data !== undefined limits the toast to failed background refetches (the user can still see old data). Initial load failures are already shown by the component or boundary, so no toast is needed.

JS Global onError in QueryCache

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second failure keeps the old value in the cache while the callback reports it as a background failure, the pattern for "stale data is better than nothing".

Mutations and errors

Mutations do not throw into boundaries unless you set throwOnError on them. Usually you handle them locally: onError for rollback (see the optimistic lessons), mutation.error for an inline message, and a MutationCache onError for global toasts.

Boundary strategy

Error kind Where to handle
Validation (400, 422) In the form, from mutation.error
Not found (404) In the component, as a normal empty state
Auth expired (401) Globally: QueryCache.onError, redirect to login
Server or network failure Error boundary with retry
Programming errors Top-level boundary and error reporting

Place boundaries like Suspense boundaries: around independent sections so one broken widget does not take down the page.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is resetting only the error boundary not enough for query errors?

    QueryErrorResetBoundary resets the queries that threw, so the retry fetches again.
  2. 2. Where should the error boundary sit relative to Suspense?

    The error boundary must wrap what throws; placing it above Suspense also lets the fallback and error UI each have their place.
  3. 3. What does throwOnError: (error) => error.status >= 500 achieve?

    The function form lets you decide per error which ones are boundary material.
  4. 4. In v5, where do you put a global toast for failed queries?

    The per-query onError, onSuccess and onSettled callbacks were removed from useQuery in v5; QueryCache callbacks run once for all queries.

Summary

  • Suspense hooks throw to error boundaries; useQuery does so with throwOnError.
  • Wrap the boundary in QueryErrorResetBoundary and call reset in onReset so retries really refetch.
  • Use the function form of throwOnError to send only unexpected errors to boundaries.
  • Use QueryCache/MutationCache callbacks for global logging and toasts.
  • Handle validation and not-found errors locally.

Next: Prefetching and Initial Data