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

suspense.md

191 lines7.3 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/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
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>
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 )
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 })
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 }
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 )
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'