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, isFetching } = useSuspenseQuery({ queryKey, queryFn })
44β
45if (error && !isFetching) {
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 = () => (
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 = () => {
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](../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 {
122 isServer,
123 QueryClient,
124 QueryClientProvider,
125} from '@tanstack/react-query'
126import * as React from 'react'
127import { ReactQueryStreamedHydration } from '@tanstack/react-query-next-experimental'
128β
129function makeQueryClient() {
130 return new QueryClient({
131 defaultOptions: {
132 queries: {
133 // With SSR, we usually want to set some default staleTime
134 // above 0 to avoid refetching immediately on the client
135 staleTime: 60 * 1000,
136 },
137 },
138 })
139}
140β
141let browserQueryClient: QueryClient | undefined = undefined
142β
143function getQueryClient() {
144 if (isServer) {
145 // Server: always make a new query client
146 return makeQueryClient()
147 } else {
148 // Browser: make a new query client if we don't already have one
149 // This is very important, so we don't re-make a new client if React
150 // suspends during the initial render. This may not be needed if we
151 // have a suspense boundary BELOW the creation of the query client
152 if (!browserQueryClient) browserQueryClient = makeQueryClient()
153 return browserQueryClient
154 }
155}
156β
157export function Providers(props: { children: React.ReactNode }) {
158 // NOTE: Avoid useState when initializing the query client if you don't
159 // have a suspense boundary between this and the code that may
160 // suspend because React will throw away the client on the initial
161 // render if it suspends and there is no boundary
162 const queryClient = getQueryClient()
163β
164 return (
165 <QueryClientProvider client={queryClient}>
166 <ReactQueryStreamedHydration>
167 {props.children}
168 </ReactQueryStreamedHydration>
169 </QueryClientProvider>
170 )
171}
172```
173β
174For more information, check out the [NextJs Suspense Streaming Example](../../examples/nextjs-suspense-streaming) and the [Advanced Rendering & Hydration](../advanced-ssr) guide.