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

suspense.md

138 lines5.9 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://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 } = useSuspenseQuery({ queryKey, queryFn })
44​
45if (error) {
46 throw error
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: React.FC = () => (
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>
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: React.FC = () => {
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 )
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](./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.
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 { QueryClient, QueryClientProvider } from '@tanstack/react-query'
122import * as React from 'react'
123import { ReactQueryStreamedHydration } from '@tanstack/react-query-next-experimental'
124​
125export function Providers(props: { children: React.ReactNode }) {
126 const [queryClient] = React.useState(() => new QueryClient())
127​
128 return (
129 <QueryClientProvider client={queryClient}>
130 <ReactQueryStreamedHydration>
131 {props.children}
132 </ReactQueryStreamedHydration>
133 </QueryClientProvider>
134 )
136```
137​
138For more information, check out the [NextJs Suspense Streaming Example](./examples/nextjs-suspense-streaming) and the [Advanced Rendering & Hydration](./guides/advanced-ssr) guide.