# Suspense and error boundaries (https://effetch-query.monarcode.dev/docs/react/suspense)

If you'd rather not render a loading state and an error state in every
component, read the query with `useSuspenseQuery`. The component renders
only when there's a value: a `Suspense` boundary shows loading, and an
error boundary shows the failure. This page shows how to set up both with
`QueryBoundary`, and how to use a router's error boundary instead.

The examples import `todos.ts` from [Getting started](https://effetch-query.monarcode.dev/docs/getting-started).

## Read with useSuspenseQuery

`useSuspenseQuery` suspends until the query has a value, then returns its
`Success`. `QueryBoundary` handles both sides around it: it shows
`pending` while the queries inside suspend, and calls `failure` when one of
them fails:

```tsx
import {
  QueryBoundary,
  useSuspenseQuery,
} from "@monarcode/effetch-query/react";

import { todo } from "./todos.js";

function TodoDetail({ id }: { readonly id: number }) {
  const { value } = useSuspenseQuery(todo({ params: { id } }));
  return <h1>{value.title}</h1>;
}

export function TodoScreen({ id }: { readonly id: number }) {
  return (
    <QueryBoundary
      key={id}
      pending={<p>Loading…</p>}
      failure={({ error, retry }) => (
        <button onClick={retry}>{String(error)}: try again</button>
      )}
    >
      <TodoDetail id={id} />
    </QueryBoundary>
  );
}
```

The `Success` stays `waiting` while the query refetches, and a refetch
that fails after a success keeps showing that success. Only a failure with
nothing to show reaches the boundary: the hook throws it as a
`QueryFailure`, which carries the query and its `Cause`.

`useSuspenseQuery` takes a query, never `null`, and its only option is
`select`: see [Select part of a value](https://effetch-query.monarcode.dev/docs/react#select-part-of-a-value).
It has no `keepPrevious` and no `paused`. To wait for an argument, render
the component only when you have it. For an infinite query, use
`useSuspenseInfiniteQuery`: see [Infinite queries](https://effetch-query.monarcode.dev/docs/queries/infinite).
To read `data`, `error` and `status` as fields instead, use
`useSuspenseQueryState`: see
[Read with Suspense](https://effetch-query.monarcode.dev/docs/react/as-object#read-with-suspense).

## Show the failure and retry

`failure` gets the failure as `error`, squashed to one value for display,
with its `cause` and `retry`. `retry` refetches the query that failed and
shows the children again.

The boundary shows `failure` until `retry` is called, or until the failed
query succeeds some other way, such as a refetch on reconnect. Because
`retry` refetches only the query that failed, give each part of a screen
that can fail on its own a boundary of its own. To show other content
after a failure, such as the next todo, give the boundary a `key`
(`key={id}`), so React makes a new one.

`QueryBoundary` catches only a `QueryFailure`. Any other error goes on to
the next error boundary up.

A `QueryFailure` has the same `error` and `cause` as `failure` gets, with
the `query` that failed. `QueryFailure.is` tells it from other errors, and
both `@monarcode/effetch-query` and `@monarcode/effetch-query/react` export
it. Code outside React never sees one: there, a query's failure keeps its
own error type.

## How suspense readers differ

A few things are particular to suspense readers:

- **A value under a second old isn't refetched on mount,** as in TanStack
  Query, so the value a component suspended on isn't fetched again as it
  mounts. An older stale value is shown and refetched in the background.
- **A failure stays thrown** until something refetches the query. A
  suspense reader never starts using the failed query, so `retryOnMount`
  doesn't retry it: `retry` or `useResetQueryFailure` does.
- **A `select` that throws** is thrown to the error boundary as a
  `QueryFailure`, even after an earlier selection was shown.
- **A placeholder counts as a value** in the browser, so the hook returns
  it rather than suspending: see
  [Tell a placeholder from the real value](https://effetch-query.monarcode.dev/docs/react/as-object#tell-a-placeholder-from-the-real-value).
- **In a server render, it fetches** a query the cache doesn't have, and
  suspends on the fetch. `useQuery` doesn't. This is what streaming a
  server render relies on: see
  [Queries started while the server renders](https://effetch-query.monarcode.dev/docs/server-rendering/streaming#queries-started-while-the-server-renders).

## Use a router's error boundary

Where a router owns the error boundary, such as TanStack Router's
`errorComponent` or a React Router `ErrorBoundary` export, call
`useResetQueryFailure` there. Given the caught error, it refetches the
query inside a `QueryFailure`, and ignores any other error. Then reset the
router's boundary:

```tsx
import {
  QueryFailure,
  useResetQueryFailure,
} from "@monarcode/effetch-query/react";
import type { ErrorComponentProps } from "@tanstack/react-router";

export function TodoFailed({ error, reset }: ErrorComponentProps) {
  const resetFailure = useResetQueryFailure();
  const shown = QueryFailure.is(error) ? error.error : error;
  return (
    <button
      onClick={() => {
        resetFailure(error);
        reset();
      }}
    >
      {String(shown)}: try again
    </button>
  );
}
```

## What's next

- [Stream the cache](https://effetch-query.monarcode.dev/docs/server-rendering/streaming): stream a server
  render, with suspense readers fetching on the server.
- [Frameworks](https://effetch-query.monarcode.dev/docs/frameworks): wire the error boundary of TanStack
  Start, Next.js or React Router.
- [Infinite queries](https://effetch-query.monarcode.dev/docs/queries/infinite): load more pages, with or
  without suspense.