Open History to see the last commit
1---
2id: suspense
3title: Suspense
4---
5β
6React Query can also be used with React's Suspense for Data Fetching API's. For this, we have dedicated hooks:
7β
8- [useSuspenseQuery](./reference/useSuspenseQuery)
9- [useSuspenseInfiniteQuery](./reference/useSuspenseInfiniteQuery)
10- [useSuspenseQueries](./reference/useSuspenseQueries)
11β
12When using suspense mode, `status` states and `error` objects are not needed and are then replaced by usage of the `React.Suspense` component (including the use of the `fallback` prop and React error boundaries for catching errors). Please read the [Resetting Error Boundaries](#resetting-error-boundaries) and look at the [Suspense Example](https://stackblitz.com/github/TanStack/query/tree/main/examples/react/suspense) for more information on how to set up suspense mode.
13β
14If you want mutations to propagate errors to the nearest error boundary (similar to queries), you can set the `throwOnError` option to `true` as well.
15β
16Enabling suspense mode for a query:
17β
18```tsx
19import { useSuspenseQuery } from '@tanstack/react-query'
20β
21const { data } = useSuspenseQuery({ queryKey, queryFn })
22```
23β
24This works nicely in TypeScript, because `data` is guaranteed to be defined (as errors and loading states are handled by Suspense- and ErrorBoundaries).
25β
26On the flip side, you therefore can't conditionally enable / disable the Query. This generally shouldn't be necessary for dependent Queries because with suspense, all your Queries inside one component are fetched in serial.
27β
28`placeholderData` also doesn't exist for this Query. To prevent the UI from being replaced by a fallback during an update, wrap your updates that change the QueryKey into [startTransition](https://react.dev/reference/react/Suspense#preventing-unwanted-fallbacks).
29β
30### throwOnError default
31β
32Not all errors are thrown to the nearest Error Boundary per default - we're only throwing errors if there is no other data to show. That means if a Query ever successfully got data in the cache, the component will render, even if data is `stale`. Thus, the default for `throwOnError` is:
33β
34```
35throwOnError: (error, query) => typeof query.state.data === 'undefined'
36```
37β
38Since you can't change `throwOnError` (because it would allow for `data` to become potentially `undefined`), you have to throw errors manually if you want all errors to be handled by Error Boundaries:
39β
40```tsx
41import { useSuspenseQuery } from '@tanstack/react-query'
42β
43const { data, error } = useSuspenseQuery({ queryKey, queryFn })
44β
45if (error) {
46 throw error
47}
48β
49// continue rendering data
50```
51β
52## Resetting Error Boundaries
53β
54Whether you are using **suspense** or **throwOnError** in your queries, you will need a way to let queries know that you want to try again when re-rendering after some error occurred.
55β
56Query errors can be reset with the `QueryErrorResetBoundary` component or with the `useQueryErrorResetBoundary` hook.
57β
58When using the component it will reset any query errors within the boundaries of the component:
59β
60```tsx
61import { QueryErrorResetBoundary } from '@tanstack/react-query'
62import { ErrorBoundary } from 'react-error-boundary'
63β
64const App: React.FC = () => (
65 <QueryErrorResetBoundary>
66 {({ reset }) => (
67 <ErrorBoundary
68 onReset={reset}
69 fallbackRender={({ resetErrorBoundary }) => (
70 <div>
71 There was an error!
72 <Button onClick={() => resetErrorBoundary()}>Try again</Button>
73 </div>
74 )}
75 >
76 <Page />
77 </ErrorBoundary>
78 )}
79 </QueryErrorResetBoundary>
80)
81```
82β
83When using the hook it will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary defined it will reset them globally:
84β
85```tsx
86import { useQueryErrorResetBoundary } from '@tanstack/react-query'
87import { ErrorBoundary } from 'react-error-boundary'
88β
89const App: React.FC = () => {
90 const { reset } = useQueryErrorResetBoundary()
91 return (
92 <ErrorBoundary
93 onReset={reset}
94 fallbackRender={({ resetErrorBoundary }) => (
95 <div>
96 There was an error!
97 <Button onClick={() => resetErrorBoundary()}>Try again</Button>
98 </div>
99 )}
100 >
101 <Page />
102 </ErrorBoundary>
103 )
104}
105```
106β
107## Fetch-on-render vs Render-as-you-fetch
108β
109Out of the box, React Query in `suspense` mode works really well as a **Fetch-on-render** solution with no additional configuration. This means that when your components attempt to mount, they will trigger query fetching and suspend, but only once you have imported them and mounted them. If you want to take it to the next level and implement a **Render-as-you-fetch** model, we recommend implementing [Prefetching](./guides/prefetching) on routing callbacks and/or user interactions events to start loading queries before they are mounted and hopefully even before you start importing or mounting their parent components.
110β
111## Suspense on the Server with streaming
112β
113If you are using `NextJs`, you can use our **experimental** integration for Suspense on the Server: `@tanstack/react-query-next-experimental`. This package will allow you to fetch data on the server (in a client component) by just calling `useSuspenseQuery` in your component. Results will then be streamed from the server to the client as SuspenseBoundaries resolve.
114β
115To achieve this, wrap your app in the `ReactQueryStreamedHydration` component:
116β
117```tsx
118// app/providers.tsx
119'use client'
120β
121import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
122import * as React from 'react'
123import { ReactQueryStreamedHydration } from '@tanstack/react-query-next-experimental'
124β
125export function Providers(props: { children: React.ReactNode }) {
126 const [queryClient] = React.useState(() => new QueryClient())
127β
128 return (
129 <QueryClientProvider client={queryClient}>
130 <ReactQueryStreamedHydration>
131 {props.children}
132 </ReactQueryStreamedHydration>
133 </QueryClientProvider>
134 )
135}
136```
137β
138For more information, check out the [NextJs Suspense Streaming Example](./examples/nextjs-suspense-streaming) and the [Advanced Rendering & Hydration](./guides/advanced-ssr) guide.