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://codesandbox.io/s/github/tannerlinsley/react-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β
53## Resetting Error Boundaries
54β
55Whether 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.
56β
57Query errors can be reset with the `QueryErrorResetBoundary` component or with the `useQueryErrorResetBoundary` hook.
58β
59When using the component it will reset any query errors within the boundaries of the component:
60β
61```tsx
62import { QueryErrorResetBoundary } from '@tanstack/react-query'
63import { ErrorBoundary } from 'react-error-boundary'
64β
65const App: React.FC = () => (
66 <QueryErrorResetBoundary>
67 {({ reset }) => (
68 <ErrorBoundary
69 onReset={reset}
70 fallbackRender={({ resetErrorBoundary }) => (
71 <div>
72 There was an error!
73 <Button onClick={() => resetErrorBoundary()}>Try again</Button>
74 </div>
75 )}
76 >
77 <Page />
78 </ErrorBoundary>
79 )}
80 </QueryErrorResetBoundary>
81)
82```
83β
84When using the hook it will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary defined it will reset them globally:
85β
86```tsx
87import { useQueryErrorResetBoundary } from '@tanstack/react-query'
88import { ErrorBoundary } from 'react-error-boundary'
89β
90const App: React.FC = () => {
91 const { reset } = useQueryErrorResetBoundary()
92 return (
93 <ErrorBoundary
94 onReset={reset}
95 fallbackRender={({ resetErrorBoundary }) => (
96 <div>
97 There was an error!
98 <Button onClick={() => resetErrorBoundary()}>Try again</Button>
99 </div>
100 )}
101 >
102 <Page />
103 </ErrorBoundary>
104 )
105}
106```
107β
108## Fetch-on-render vs Render-as-you-fetch
109β
110Out 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.
111β
112## Suspense on the Server with streaming
113β
114If 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 `useQuery` (with `suspense: true`) or `useSuspenseQuery` in your component. Results will then be streamed from the server to the client as SuspenseBoundaries resolve.
115β
116To achieve this, wrap your app in the `ReactQueryStreamedHydration` component:
117β
118```tsx
119// app/providers.tsx
120'use client'
121β
122import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
123import * as React from 'react'
124import { ReactQueryStreamedHydration } from '@tanstack/react-query-next-experimental'
125β
126export function Providers(props: { children: React.ReactNode }) {
127 const [queryClient] = React.useState(() => new QueryClient())
128β
129 return (
130 <QueryClientProvider client={queryClient}>
131 <ReactQueryStreamedHydration>
132 {props.children}
133 </ReactQueryStreamedHydration>
134 </QueryClientProvider>
135 )
136}
137```
138β
139For more information, check out the [NextJs Suspense Streaming Example](../examples/react/nextjs-suspense-streaming).
140β
141## Further reading
142β
143For tips on using suspense option, check the [Suspensive React Query Package](../community/suspensive-react-query) from the Community Resources.