Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

suspense.md

224 lines8.1 KB

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/useSuspenseQuery.md)
9- [useSuspenseInfiniteQuery](../reference/useSuspenseInfiniteQuery.md)
10- [useSuspenseQueries](../reference/useSuspenseQueries.md)
11- Additionally, you can use the `useQuery().promise` and `React.use()` (Experimental)
12​
13When 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/react/suspense) for more information on how to set up suspense mode.
14​
15If you want mutations to propagate errors to the nearest error boundary (similar to queries), you can set the `throwOnError` option to `true` as well.
16​
17Enabling suspense mode for a query:
18​
19```tsx
20import { useSuspenseQuery } from '@tanstack/react-query'
21​
22const { data } = useSuspenseQuery({ queryKey, queryFn })
23```
24​
25This works nicely in TypeScript, because `data` is guaranteed to be defined (as errors and loading states are handled by Suspense- and ErrorBoundaries).
26​
27On 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.
28​
29`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).
30​
31### throwOnError default
32​
33Not 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:
34​
35```
36throwOnError: (error, query) => typeof query.state.data === 'undefined'
37```
38​
39Since 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:
40​
41```tsx
42import { useSuspenseQuery } from '@tanstack/react-query'
43​
44const { data, error, isFetching } = useSuspenseQuery({ queryKey, queryFn })
45​
46if (error && !isFetching) {
47 throw error
49​
50// continue rendering data
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 = () => (
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>
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 = () => {
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 )
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](./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.
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 `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 {
123 isServer,
124 QueryClient,
125 QueryClientProvider,
126} from '@tanstack/react-query'
127import * as React from 'react'
128import { ReactQueryStreamedHydration } from '@tanstack/react-query-next-experimental'
129​
130function makeQueryClient() {
131 return new QueryClient({
132 defaultOptions: {
133 queries: {
134 // With SSR, we usually want to set some default staleTime
135 // above 0 to avoid refetching immediately on the client
136 staleTime: 60 * 1000,
137 },
138 },
139 })
141​
142let browserQueryClient: QueryClient | undefined = undefined
143​
144function getQueryClient() {
145 if (isServer) {
146 // Server: always make a new query client
147 return makeQueryClient()
148 } else {
149 // Browser: make a new query client if we don't already have one
150 // This is very important, so we don't re-make a new client if React
151 // suspends during the initial render. This may not be needed if we
152 // have a suspense boundary BELOW the creation of the query client
153 if (!browserQueryClient) browserQueryClient = makeQueryClient()
154 return browserQueryClient
155 }
157​
158export function Providers(props: { children: React.ReactNode }) {
159 // NOTE: Avoid useState when initializing the query client if you don't
160 // have a suspense boundary between this and the code that may
161 // suspend because React will throw away the client on the initial
162 // render if it suspends and there is no boundary
163 const queryClient = getQueryClient()
164​
165 return (
166 <QueryClientProvider client={queryClient}>
167 <ReactQueryStreamedHydration>
168 {props.children}
169 </ReactQueryStreamedHydration>
170 </QueryClientProvider>
171 )
173```
174​
175For more information, check out the [NextJs Suspense Streaming Example](../examples/react/nextjs-suspense-streaming) and the [Advanced Rendering & Hydration](./advanced-ssr.md) guide.
176​
177## Using `useQuery().promise` and `React.use()` (Experimental)
178​
179> To enable this feature, you need to set the `experimental_prefetchInRender` option to `true` when creating your `QueryClient`
180​
181**Example code:**
182​
183```tsx
184const queryClient = new QueryClient({
185 defaultOptions: {
186 queries: {
187 experimental_prefetchInRender: true,
188 },
189 },
190})
191```
192​
193**Usage:**
194​
195```tsx
196import React from 'react'
197import { useQuery } from '@tanstack/react-query'
198import { fetchTodos, type Todo } from './api'
199​
200function TodoList({ query }: { query: UseQueryResult<Todo[]> }) {
201 const data = React.use(query.promise)
202​
203 return (
204 <ul>
205 {data.map((todo) => (
206 <li key={todo.id}>{todo.title}</li>
207 ))}
208 </ul>
209 )
211​
212export function App() {
213 const query = useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
214​
215 return (
216 <>
217 <h1>Todos</h1>
218 <React.Suspense fallback={<div>Loading...</div>}>
219 <TodoList query={query} />
220 </React.Suspense>
221 </>
222 )
224```