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

advanced-ssr.md

662 lines28.0 KB

1---
2id: advanced-ssr
3title: Advanced Server Rendering
4---
5​
6Welcome to the Advanced Server Rendering guide, where you will learn all about using React Query with streaming, Server Components and the Next.js app router.
7​
8You might want to read the [Server Rendering & Hydration guide](./ssr.md) before this one as it teaches the basics for using React Query with SSR, and [Performance & Request Waterfalls](./request-waterfalls.md) as well as [Prefetching & Router Integration](./prefetching.md) also contains valuable background.
9​
10Before we start, let's note that while the `initialData` approach outlined in the SSR guide also works with Server Components, we'll focus this guide on the hydration APIs.
11​
12## Server Components & Next.js app router
13​
14We won't cover Server Components in depth here, but the short version is that they are components that are guaranteed to _only_ run on the server, both for the initial page view and **also on page transitions**. This is similar to how Next.js `getServerSideProps`/`getStaticProps` and Remix `loader` works, as these also always run on the server but while those can only return data, Server Components can do a lot more. The data part is central to React Query however, so let's focus on that.
15​
16How do we take what we learned in the Server Rendering guide about [passing data prefetched in framework loaders to the app](./ssr.md#using-the-hydration-apis) and apply that to Server Components and the Next.js app router? The best way to start thinking about this is to consider Server Components as "just" another framework loader.
17​
18### A quick note on terminology
19​
20So far in these guides, we've been talking about the _server_ and the _client_. It's important to note that confusingly enough this does not match 1-1 with _Server Components_ and _Client Components_. Server Components are guaranteed to only run on the server, but Client Components can actually run in both places. The reason for this is that they can also render during the initial _server rendering_ pass.
21​
22One way to think of this is that even though Server Components also _render_, they happen during a "loader phase" (always happens on the server), while Client Components run during the "application phase". That application can run both on the server during SSR, and in for example a browser. Where exactly that application runs and if it runs during SSR or not might differ between frameworks.
23​
24### Initial setup
25​
26The first step of any React Query setup is always to create a `queryClient` and wrap your application in a `QueryClientProvider`. With Server Components, this looks mostly the same across frameworks, one difference being the filename conventions:
27​
28```tsx
29// In Next.js, this file would be called: app/providers.tsx
30'use client'
31​
32// Since QueryClientProvider relies on useContext under the hood, we have to put 'use client' on top
33import {
34 environmentManager,
35 QueryClient,
36 QueryClientProvider,
37} from '@tanstack/react-query'
38​
39function makeQueryClient() {
40 return new QueryClient({
41 defaultOptions: {
42 queries: {
43 // With SSR, we usually want to set some default staleTime
44 // above 0 to avoid refetching immediately on the client
45 staleTime: 60 * 1000,
46 },
47 },
48 })
50​
51let browserQueryClient: QueryClient | undefined = undefined
52​
53function getQueryClient() {
54 if (environmentManager.isServer()) {
55 // Server: always make a new query client
56 return makeQueryClient()
57 } else {
58 // Browser: make a new query client if we don't already have one
59 // This is very important, so we don't re-make a new client if React
60 // suspends during the initial render. This may not be needed if we
61 // have a suspense boundary BELOW the creation of the query client
62 if (!browserQueryClient) browserQueryClient = makeQueryClient()
63 return browserQueryClient
64 }
66​
67export default function Providers({ children }: { children: React.ReactNode }) {
68 // NOTE: Avoid useState when initializing the query client if you don't
69 // have a suspense boundary between this and the code that may
70 // suspend because React will throw away the client on the initial
71 // render if it suspends and there is no boundary
72 const queryClient = getQueryClient()
73​
74 return (
75 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
76 )
78```
79​
80```tsx
81// In Next.js, this file would be called: app/layout.tsx
82import Providers from './providers'
83​
84export default function RootLayout({
85 children,
86}: {
87 children: React.ReactNode
88}) {
89 return (
90 <html lang="en">
91 <head />
92 <body>
93 <Providers>{children}</Providers>
94 </body>
95 </html>
96 )
98```
99​
100This part is pretty similar to what we did in the SSR guide, we just need to split things up into two different files.
101​
102### Prefetching and de/hydrating data
103​
104Next, let’s look at how to actually prefetch data, then dehydrate and hydrate it. This is what it looked like using the **Next.js Pages Router**:
105​
106```tsx
107// pages/posts.tsx
108import {
109 dehydrate,
110 HydrationBoundary,
111 QueryClient,
112 useQuery,
113} from '@tanstack/react-query'
114​
115// This could also be getServerSideProps
116export async function getStaticProps() {
117 const queryClient = new QueryClient()
118​
119 await queryClient
120 .query({
121 queryKey: ['posts'],
122 queryFn: getPosts,
123 })
124 .catch(noop)
125​
126 return {
127 props: {
128 dehydratedState: dehydrate(queryClient),
129 },
130 }
132​
133function Posts() {
134 // This useQuery could just as well happen in some deeper child to
135 // the <PostsRoute>, data will be available immediately either way
136 //
137 // Note that we are using useQuery here instead of useSuspenseQuery.
138 // Because this data has already been prefetched, there is no need to
139 // ever suspend in the component itself. If we forget or remove the
140 // prefetch, this will instead fetch the data on the client, while
141 // using useSuspenseQuery would have had worse side effects.
142 const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
143​
144 // This query was not prefetched on the server and will not start
145 // fetching until on the client, both patterns are fine to mix
146 const { data: commentsData } = useQuery({
147 queryKey: ['posts-comments'],
148 queryFn: getComments,
149 })
150​
151 // ...
153​
154export default function PostsRoute({ dehydratedState }) {
155 return (
156 <HydrationBoundary state={dehydratedState}>
157 <Posts />
158 </HydrationBoundary>
159 )
161```
162​
163Converting this to the app router actually looks pretty similar, we just need to move things around a bit. First, we'll create a Server Component to do the prefetching part:
164​
165```tsx
166// app/posts/page.tsx
167import {
168 dehydrate,
169 HydrationBoundary,
170 QueryClient,
171} from '@tanstack/react-query'
172import Posts from './posts'
173​
174export default async function PostsPage() {
175 const queryClient = new QueryClient()
176​
177 await queryClient
178 .query({
179 queryKey: ['posts'],
180 queryFn: getPosts,
181 })
182 .catch(noop)
183​
184 return (
185 // Neat! Serialization is now as easy as passing props.
186 // HydrationBoundary is a Client Component, so hydration will happen there.
187 <HydrationBoundary state={dehydrate(queryClient)}>
188 <Posts />
189 </HydrationBoundary>
190 )
192```
193​
194Next, we'll look at what the Client Component part looks like:
195​
196```tsx
197// app/posts/posts.tsx
198'use client'
199​
200export default function Posts() {
201 // This useQuery could just as well happen in some deeper
202 // child to <Posts>, data will be available immediately either way
203 const { data } = useQuery({
204 queryKey: ['posts'],
205 queryFn: () => getPosts(),
206 })
207​
208 // This query was not prefetched on the server and will not start
209 // fetching until on the client, both patterns are fine to mix.
210 const { data: commentsData } = useQuery({
211 queryKey: ['posts-comments'],
212 queryFn: getComments,
213 })
214​
215 // ...
217```
218​
219One neat thing about the examples above is that the only thing that is Next.js-specific here are the file names, everything else would look the same in any other framework that supports Server Components.
220​
221In the SSR guide, we noted that you could get rid of the boilerplate of having `<HydrationBoundary>` in every route. This is not possible with Server Components.
222​
223> NOTE: If you encounter a type error while using async Server Components with TypeScript versions lower than `5.1.3` and `@types/react` versions lower than `18.2.8`, it is recommended to update to the latest versions of both. Alternatively, you can use the temporary workaround of adding `{/* @ts-expect-error Server Component */}` when calling this component inside another. For more information, see [Async Server Component TypeScript Error](https://nextjs.org/docs/app/building-your-application/configuring/typescript#async-server-component-typescript-error) in the Next.js TypeScript docs.
224​
225> WARNING: We do **not** recommend using Next.js Server Actions to _fetch_ data in a `queryFn`. When called from the client, Server Actions [run serially, not in parallel](https://react.dev/reference/rsc/use-server#caveats), which conflicts with how React Query fetches and refetches queries. This can leave queries stuck in a pending state or cause the action to never run at all (see [#7934](https://github.com/TanStack/query/issues/7934)). Passing a Server Action reference to `queryFn` can also fail with `Only plain objects, and a few built-ins, can be passed to Server Actions...`, since you have to _call_ the action rather than pass it as a reference (see [#6264](https://github.com/TanStack/query/issues/6264)). For fetching data on the client, `fetch` from an API route or use an RPC layer such as tRPC instead. Server Actions remain a good fit for **mutations** (`useMutation`).
226​
227### Nesting Server Components
228​
229A nice thing about Server Components is that they can be nested and exist on many levels in the React tree, making it possible to prefetch data closer to where it's actually used instead of only at the top of the application (just like Remix loaders). This can be as simple as a Server Component rendering another Server Component (we'll leave the Client Components out in this example for brevity):
230​
231```tsx
232// app/posts/page.tsx
233import {
234 dehydrate,
235 HydrationBoundary,
236 QueryClient,
237} from '@tanstack/react-query'
238import Posts from './posts'
239import CommentsServerComponent from './comments-server'
240​
241export default async function PostsPage() {
242 const queryClient = new QueryClient()
243​
244 await queryClient
245 .query({
246 queryKey: ['posts'],
247 queryFn: getPosts,
248 })
249 .catch(noop)
250​
251 return (
252 <HydrationBoundary state={dehydrate(queryClient)}>
253 <Posts />
254 <CommentsServerComponent />
255 </HydrationBoundary>
256 )
258​
259// app/posts/comments-server.tsx
260import {
261 dehydrate,
262 HydrationBoundary,
263 QueryClient,
264} from '@tanstack/react-query'
265import Comments from './comments'
266​
267export default async function CommentsServerComponent() {
268 const queryClient = new QueryClient()
269​
270 await queryClient
271 .query({
272 queryKey: ['posts-comments'],
273 queryFn: getComments,
274 })
275 .catch(noop)
276​
277 return (
278 <HydrationBoundary state={dehydrate(queryClient)}>
279 <Comments />
280 </HydrationBoundary>
281 )
283```
284​
285As you can see, it's perfectly fine to use `<HydrationBoundary>` in multiple places, and create and dehydrate multiple `queryClient` for prefetching.
286​
287Note that because we are awaiting `getPosts` before rendering `CommentsServerComponent` this would lead to a server side waterfall:
288​
289```
2901. |> getPosts()
2912. |> getComments()
292```
293​
294If the server latency to the data is low, this might not be a huge issue, but is still worth pointing out.
295​
296In Next.js, besides prefetching data in `page.tsx`, you can also do it in `layout.tsx`, and in [parallel routes](https://nextjs.org/docs/app/building-your-application/routing/parallel-routes). Because these are all part of the routing, Next.js knows how to fetch them all in parallel. So if `CommentsServerComponent` above was instead expressed as a parallel route, the waterfall would be flattened automatically.
297​
298As more frameworks start supporting Server Components, they might have other routing conventions. Read your framework docs for details.
299​
300### Alternative: Use a single `queryClient` for prefetching
301​
302In the example above, we create a new `queryClient` for each Server Component that fetches data. This is the recommended approach, but if you want to, you can alternatively create a single one that is reused across all Server Components:
303​
304```tsx
305// app/getQueryClient.tsx
306import { QueryClient } from '@tanstack/react-query'
307import { cache } from 'react'
308​
309// cache() is scoped per request, so we don't leak data between requests
310const getQueryClient = cache(() => new QueryClient())
311export default getQueryClient
312```
313​
314The benefit of this is that you can call `getQueryClient()` to get a hold of this client anywhere that gets called from a Server Component, including utility functions. The downside is that every time you call `dehydrate(getQueryClient())`, you serialize _the entire_ `queryClient`, including queries that have already been serialized before and are unrelated to the current Server Component which is unnecessary overhead.
315​
316Next.js already dedupes requests that utilize `fetch()`, but if you are using something else in your `queryFn`, or if you use a framework that does _not_ dedupe these requests automatically, using a single `queryClient` as described above might make sense, despite the duplicated serialization.
317​
318> As a future improvement, we might look into creating a `dehydrateNew()` function (name pending) that only dehydrate queries that are _new_ since the last call to `dehydrateNew()`. Feel free to get in touch if this sounds interesting and like something you want to help out with!
319​
320### Data ownership and revalidation
321​
322With Server Components, it's important to think about data ownership and revalidation. To explain why, let's look at a modified example from above:
323​
324```tsx
325// app/posts/page.tsx
326import {
327 dehydrate,
328 HydrationBoundary,
329 QueryClient,
330} from '@tanstack/react-query'
331import Posts from './posts'
332​
333export default async function PostsPage() {
334 const queryClient = new QueryClient()
335​
336 // Note we are getting the result from query
337 const posts = await queryClient.query({
338 queryKey: ['posts'],
339 queryFn: getPosts,
340 })
341​
342 return (
343 <HydrationBoundary state={dehydrate(queryClient)}>
344 {/* This is the new part */}
345 <div>Nr of posts: {posts.length}</div>
346 <Posts />
347 </HydrationBoundary>
348 )
350```
351​
352We are now rendering data from the `getPosts` query both in a Server Component and in a Client Component. This will be fine for the initial page render, but what happens when the query revalidates on the client for some reason when `staleTime` has been passed?
353​
354React Query has no idea of how to _revalidate the Server Component_, so if it refetches the data on the client, causing React to rerender the list of posts, the `Nr of posts: {posts.length}` will end up out of sync.
355​
356This is fine if you set `staleTime: Infinity`, so that React Query never revalidates, but this is probably not what you want if you are using React Query in the first place.
357​
358Using React Query with Server Components makes most sense if:
359​
360- You have an app using React Query and want to migrate to Server Components without rewriting all the data fetching
361- You want a familiar programming paradigm, but want to still sprinkle in the benefits of Server Components where it makes most sense
362- You have some use case that React Query covers, but that your framework of choice does not cover
363​
364It's hard to give general advice on when it makes sense to pair React Query with Server Components and not. **If you are just starting out with a new Server Components app, we suggest you start out with any tools for data fetching your framework provides you with and avoid bringing in React Query until you actually need it.** This might be never, and that's fine, use the right tool for the job!
365​
366If you do use it, a good rule of thumb is to avoid rendering the result of `queryClient.query` on the server or passing it to another component, even a Client Component one.
367​
368From the React Query perspective, treat Server Components as a place to prefetch data, nothing more.
369​
370Of course, it's fine to have Server Components own some data, and Client Components own other, just make sure those two realities don't get out of sync.
371​
372## Streaming with Server Components
373​
374The Next.js app router automatically streams any part of the application that is ready to be displayed to the browser as soon as possible, so finished content can be displayed immediately without waiting for still pending content. It does this along `<Suspense>` boundary lines. Note that if you create a file `loading.tsx`, this automatically creates a `<Suspense>` boundary behind the scenes.
375​
376With the prefetching patterns described above, React Query is perfectly compatible with this form of streaming. As the data for each Suspense boundary resolves, Next.js can render and stream the finished content to the browser. This works even if you are using `useQuery` as outlined above because the suspending actually happens when you `await` the prefetch.
377​
378As of React Query v5.40.0, you don't have to `await` all prefetches for this to work, as `pending` Queries can also be dehydrated and sent to the client. This lets you kick off prefetches as early as possible without letting them block an entire Suspense boundary, and streams the _data_ to the client as the query finishes. This can be useful for example if you want to prefetch some content that is only visible after some user interaction, or say if you want to `await` and render the first page of an infinite query, but start prefetching page 2 without blocking rendering.
379​
380To make this work, we have to instruct the `queryClient` to also `dehydrate` pending Queries. We can do this globally, or by passing that option directly to `dehydrate`.
381​
382We will also need to move the `getQueryClient()` function out of our `app/providers.tsx` file as we want to use it in our server component and our client provider.
383​
384```tsx
385// app/get-query-client.ts
386import {
387 environmentManager,
388 QueryClient,
389 defaultShouldDehydrateQuery,
390} from '@tanstack/react-query'
391​
392function makeQueryClient() {
393 return new QueryClient({
394 defaultOptions: {
395 queries: {
396 staleTime: 60 * 1000,
397 },
398 dehydrate: {
399 // include pending queries in dehydration
400 shouldDehydrateQuery: (query) =>
401 defaultShouldDehydrateQuery(query) ||
402 query.state.status === 'pending',
403 shouldRedactErrors: (error) => {
404 // We should not catch Next.js server errors
405 // as that's how Next.js detects dynamic pages
406 // so we cannot redact them.
407 // Next.js also automatically redacts errors for us
408 // with better digests.
409 return false
410 },
411 },
412 },
413 })
415​
416let browserQueryClient: QueryClient | undefined = undefined
417​
418export function getQueryClient() {
419 if (environmentManager.isServer()) {
420 // Server: always make a new query client
421 return makeQueryClient()
422 } else {
423 // Browser: make a new query client if we don't already have one
424 // This is very important, so we don't re-make a new client if React
425 // suspends during the initial render. This may not be needed if we
426 // have a suspense boundary BELOW the creation of the query client
427 if (!browserQueryClient) browserQueryClient = makeQueryClient()
428 return browserQueryClient
429 }
431```
432​
433> Note: This works in NextJs and Server Components because React can serialize Promises over the wire when you pass them down to Client Components.
434​
435Then, all we need to do is provide a `HydrationBoundary`, but we don't need to `await` prefetches anymore:
436​
437```tsx
438// app/posts/page.tsx
439import { dehydrate, HydrationBoundary } from '@tanstack/react-query'
440import { getQueryClient } from './get-query-client'
441import Posts from './posts'
442​
443// the function doesn't need to be `async` because we don't `await` anything
444export default function PostsPage() {
445 const queryClient = getQueryClient()
446​
447 // look ma, no await
448 void queryClient
449 .query({
450 queryKey: ['posts'],
451 queryFn: getPosts,
452 })
453 .catch(noop)
454​
455 return (
456 <HydrationBoundary state={dehydrate(queryClient)}>
457 <Posts />
458 </HydrationBoundary>
459 )
461```
462​
463On the client, the Promise will be put into the QueryCache for us. That means we can now call `useSuspenseQuery` inside the `Posts` component to "use" that Promise (which was created on the Server):
464​
465```tsx
466// app/posts/posts.tsx
467'use client'
468​
469export default function Posts() {
470 const { data } = useSuspenseQuery({ queryKey: ['posts'], queryFn: getPosts })
471​
472 // ...
474```
475​
476> Note that you could also `useQuery` instead of `useSuspenseQuery`, and the Promise would still be picked up correctly. However, NextJs won't suspend in that case and the component will render in the `pending` status, which also opts out of server rendering the content.
477​
478If you're using non-JSON data types and serialize the query results on the server, you can specify the `dehydrate.serializeData` and `hydrate.deserializeData` options to serialize and deserialize the data on each side of the boundary to ensure the data in the cache is the same format both on the server and the client:
479​
480```tsx
481// app/get-query-client.ts
482import { QueryClient, defaultShouldDehydrateQuery } from '@tanstack/react-query'
483import { deserialize, serialize } from './transformer'
484​
485function makeQueryClient() {
486 return new QueryClient({
487 defaultOptions: {
488 // ...
489 hydrate: {
490 deserializeData: deserialize,
491 },
492 dehydrate: {
493 serializeData: serialize,
494 },
495 },
496 })
498​
499// ...
500```
501​
502```tsx
503// app/posts/page.tsx
504import {
505 dehydrate,
506 HydrationBoundary,
507 QueryClient,
508} from '@tanstack/react-query'
509import { getQueryClient } from './get-query-client'
510import { serialize } from './transformer'
511import Posts from './posts'
512​
513export default function PostsPage() {
514 const queryClient = getQueryClient()
515​
516 // look ma, no await
517 void queryClient
518 .query({
519 queryKey: ['posts'],
520 queryFn: () => getPosts().then(serialize), // <-- serialize the data on the server
521 })
522 .catch(noop)
523​
524 return (
525 <HydrationBoundary state={dehydrate(queryClient)}>
526 <Posts />
527 </HydrationBoundary>
528 )
530```
531​
532```tsx
533// app/posts/posts.tsx
534'use client'
535​
536export default function Posts() {
537 const { data } = useSuspenseQuery({ queryKey: ['posts'], queryFn: getPosts })
538​
539 // ...
541```
542​
543Now, your `getPosts` function can return e.g. `Temporal` datetime objects and the data will be serialized and deserialized on the client, assuming your transformer can serialize and deserialize those data types.
544​
545For more information, check out the [Next.js App with Prefetching Example](../examples/nextjs-app-prefetching).
546​
547### Using the Persist Adapter with Streaming
548​
549If you're using the persist adapter with the [Streaming with Server Components](#streaming-with-server-components) feature, you need to be careful not to save promises to storage. Since pending queries can be dehydrated and streamed to the client, you should configure the persister to only persist successful queries:
550​
551```tsx
552<PersistQueryClientProvider
553 client={queryClient}
554 persistOptions={{
555 persister,
556 // We don't want to save promises into the storage, so we only persist successful queries
557 dehydrateOptions: { shouldDehydrateQuery: defaultShouldDehydrateQuery },
558 }}
560 {children}
561</PersistQueryClientProvider>
562```
563​
564This ensures that only successfully resolved queries are persisted to storage, preventing serialization issues with pending promises.
565​
566## Experimental streaming without prefetching in Next.js
567​
568While we recommend the prefetching solution detailed above because it flattens request waterfalls both on the initial page load **and** any subsequent page navigation, there is an experimental way to skip prefetching altogether and still have streaming SSR work: `@tanstack/react-query-next-experimental`
569​
570This 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. If you call `useSuspenseQuery` without wrapping it in a `<Suspense>` boundary, the HTML response won't start until the fetch resolves. This can be what you want depending on the situation, but keep in mind that this will hurt your TTFB.
571​
572To achieve this, wrap your app in the `ReactQueryStreamedHydration` component:
573​
574```tsx
575// app/providers.tsx
576'use client'
577​
578import {
579 environmentManager,
580 QueryClient,
581 QueryClientProvider,
582} from '@tanstack/react-query'
583import * as React from 'react'
584import { ReactQueryStreamedHydration } from '@tanstack/react-query-next-experimental'
585​
586function makeQueryClient() {
587 return new QueryClient({
588 defaultOptions: {
589 queries: {
590 // With SSR, we usually want to set some default staleTime
591 // above 0 to avoid refetching immediately on the client
592 staleTime: 60 * 1000,
593 },
594 },
595 })
597​
598let browserQueryClient: QueryClient | undefined = undefined
599​
600function getQueryClient() {
601 if (environmentManager.isServer()) {
602 // Server: always make a new query client
603 return makeQueryClient()
604 } else {
605 // Browser: make a new query client if we don't already have one
606 // This is very important, so we don't re-make a new client if React
607 // suspends during the initial render. This may not be needed if we
608 // have a suspense boundary BELOW the creation of the query client
609 if (!browserQueryClient) browserQueryClient = makeQueryClient()
610 return browserQueryClient
611 }
613​
614export function Providers(props: { children: React.ReactNode }) {
615 // NOTE: Avoid useState when initializing the query client if you don't
616 // have a suspense boundary between this and the code that may
617 // suspend because React will throw away the client on the initial
618 // render if it suspends and there is no boundary
619 const queryClient = getQueryClient()
620​
621 return (
622 <QueryClientProvider client={queryClient}>
623 <ReactQueryStreamedHydration>
624 {props.children}
625 </ReactQueryStreamedHydration>
626 </QueryClientProvider>
627 )
629```
630​
631For more information, check out the [NextJs Suspense Streaming Example](../examples/nextjs-suspense-streaming).
632​
633The big upside is that you no longer need to prefetch queries manually to have SSR work, and it even still streams in the result! This gives you phenomenal DX and lower code complexity.
634​
635The downside is easiest to explain if we look back at [the complex request waterfall example](./request-waterfalls.md#code-splitting) in the Performance & Request Waterfalls guide. Server Components with prefetching effectively eliminates the request waterfalls both for the initial page load **and** any subsequent navigation. This prefetch-less approach however will only flatten the waterfalls on the initial page load but ends up the same deep waterfall as the original example on page navigations:
636​
637```
6381. |> JS for <Feed>
6392. |> getFeed()
6403. |> JS for <GraphFeedItem>
6414. |> getGraphDataById()
642```
643​
644This is even worse than with `getServerSideProps`/`getStaticProps`, since with those we could at least parallelize data- and code-fetching.
645​
646If you value DX/iteration/shipping speed with low code complexity over performance, don't have deeply nested queries, or are on top of your request waterfalls with parallel fetching using tools like `useSuspenseQueries`, this can be a good tradeoff.
647​
648> It might be possible to combine the two approaches, but even we haven't tried that out yet. If you do try this, please report back your findings, or even update these docs with some tips!
649​
650## Final words
651​
652Server Components and streaming are still fairly new concepts and we are still figuring out how React Query fits in and what improvements we can make to the API. We welcome suggestions, feedback and bug reports!
653​
654Similarly, it would be impossible to teach all the intricacies of this new paradigm all in one guide, on the first try. If you are missing some piece of information here or have suggestions on how to improve this content, also get in touch, or even better, click the "Edit on GitHub" button below and help us out.
655​
656[//]: # 'Materials'
657​
658## Further reading
659​
660To understand if your application can benefit from React Query when also using Server Components, see the article [You Might Not Need React Query](https://tkdodo.eu/blog/you-might-not-need-react-query).
661​
662[//]: # 'Materials'