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 APIs. For this, we have dedicated hooks:
7β
8- [useSuspenseQuery](../reference/functions/useSuspenseQuery.md)
9- [useSuspenseInfiniteQuery](../reference/functions/useSuspenseInfiniteQuery.md)
10- [useSuspenseQueries](../reference/functions/useSuspenseQueries.md)
11β
12[//]: # 'Info'
13β
14When 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](../examples/suspense) for more information on how to set up suspense mode.
15[//]: # 'Info'
16β
17If you want mutations to propagate errors to the nearest error boundary (similar to queries), you can set the `throwOnError` option to `true` as well.
18β
19Enabling suspense mode for a query:
20β
21```tsx
22import { useSuspenseQuery } from '@tanstack/react-query'
23β
24const { data } = useSuspenseQuery({ queryKey, queryFn })
25```
26β
27This works nicely in TypeScript, because `data` is guaranteed to be defined (as errors and loading states are handled by Suspense- and ErrorBoundaries).
28β
29On 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.
30β
31[//]: # 'PlaceholderData'
32β
33`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).
34[//]: # 'PlaceholderData'
35β
36### throwOnError default
37β
38Not 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:
39β
40```
41throwOnError: (error, query) => typeof query.state.data === 'undefined'
42```
43β
44Since 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:
45β
46```tsx
47import { useSuspenseQuery } from '@tanstack/react-query'
48β
49const { data, error, isFetching } = useSuspenseQuery({ queryKey, queryFn })
50β
51if (error && !isFetching) {
52 throw error
53}
54β
55// continue rendering data
56```
57β
58## Resetting Error Boundaries
59β
60Whether 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.
61β
62Query errors can be reset with the `QueryErrorResetBoundary` component or with the `useQueryErrorResetBoundary` hook.
63β
64When using the component it will reset any query errors within the boundaries of the component:
65β
66[//]: # 'ExampleResetComponent'
67β
68```tsx
69import { QueryErrorResetBoundary } from '@tanstack/react-query'
70import { ErrorBoundary } from 'react-error-boundary'
71β
72const App = () => (
73 <QueryErrorResetBoundary>
74 {({ reset }) => (
75 <ErrorBoundary
76 onReset={reset}
77 fallbackRender={({ resetErrorBoundary }) => (
78 <div>
79 There was an error!
80 <button onClick={() => resetErrorBoundary()}>Try again</button>
81 </div>
82 )}
83 >
84 <Page />
85 </ErrorBoundary>
86 )}
87 </QueryErrorResetBoundary>
88)
89```
90β
91[//]: # 'ExampleResetComponent'
92β
93When using the hook it will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary defined it will reset them globally:
94β
95[//]: # 'ExampleResetHook'
96β
97```tsx
98import { useQueryErrorResetBoundary } from '@tanstack/react-query'
99import { ErrorBoundary } from 'react-error-boundary'
100β
101const App = () => {
102 const { reset } = useQueryErrorResetBoundary()
103 return (
104 <ErrorBoundary
105 onReset={reset}
106 fallbackRender={({ resetErrorBoundary }) => (
107 <div>
108 There was an error!
109 <button onClick={() => resetErrorBoundary()}>Try again</button>
110 </div>
111 )}
112 >
113 <Page />
114 </ErrorBoundary>
115 )
116}
117```
118β
119[//]: # 'ExampleResetHook'
120β
121## Fetch-on-render vs Render-as-you-fetch
122β
123Out 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.md) 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.
124β
125[//]: # 'Streaming'
126β
127## Suspense on the Server with streaming
128β
129If 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.
130β
131To achieve this, wrap your app in the `ReactQueryStreamedHydration` component:
132β
133```tsx
134// app/providers.tsx
135'use client'
136β
137import {
138 environmentManager,
139 QueryClient,
140 QueryClientProvider,
141} from '@tanstack/react-query'
142import * as React from 'react'
143import { ReactQueryStreamedHydration } from '@tanstack/react-query-next-experimental'
144β
145function makeQueryClient() {
146 return new QueryClient({
147 defaultOptions: {
148 queries: {
149 // With SSR, we usually want to set some default staleTime
150 // above 0 to avoid refetching immediately on the client
151 staleTime: 60 * 1000,
152 },
153 },
154 })
155}
156β
157let browserQueryClient: QueryClient | undefined = undefined
158β
159function getQueryClient() {
160 if (environmentManager.isServer()) {
161 // Server: always make a new query client
162 return makeQueryClient()
163 } else {
164 // Browser: make a new query client if we don't already have one
165 // This is very important, so we don't re-make a new client if React
166 // suspends during the initial render. This may not be needed if we
167 // have a suspense boundary BELOW the creation of the query client
168 if (!browserQueryClient) browserQueryClient = makeQueryClient()
169 return browserQueryClient
170 }
171}
172β
173export function Providers(props: { children: React.ReactNode }) {
174 // NOTE: Avoid useState when initializing the query client if you don't
175 // have a suspense boundary between this and the code that may
176 // suspend because React will throw away the client on the initial
177 // render if it suspends and there is no boundary
178 const queryClient = getQueryClient()
179β
180 return (
181 <QueryClientProvider client={queryClient}>
182 <ReactQueryStreamedHydration>
183 {props.children}
184 </ReactQueryStreamedHydration>
185 </QueryClientProvider>
186 )
187}
188```
189β
190For more information, check out the [NextJs Suspense Streaming Example](../examples/nextjs-suspense-streaming) and the [Advanced Rendering & Hydration](./advanced-ssr.md) guide.
191[//]: # 'Streaming'