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

suspense.md

143 lines6.1 KB

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
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>
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 )
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 )
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.