Skip to content
Source
Sign inSign up
TanStack/query

fix(react-query): render dehydrated pending queries as pending during hydration #12697

ClosedDogPawHatwants to merge 2 commits intoquery-v6 fromrefs/pull/12697/headopened View on GitHub

Showing 10 changed files with 194 additions and 0 deletions (loading 7).

x
0 of 10 viewed, 10 left
6 additions and 0 deletions.changeset/pending-hydration-server-snapshot.mdAdded
View file
@@ -0,0 +1,6 @@
+---
+'@tanstack/query-core': minor
+'@tanstack/react-query': patch
+---
+​
+Add `getServerSnapshot` to query result readers. For a query that `hydrate` created, it computes the result from the state the query was hydrated with, so server renders and client hydration renders show the same result even if the query changes in between, for example when a streamed promise resolves or a refetch finishes. A query that was dehydrated while pending renders as pending until hydration finishes. This fixes hydration mismatches in `useQuery`, `useInfiniteQuery` and `useQueries`. Suspense hooks are unchanged.
2 additions and 0 deletionsdocs/framework/react/guides/advanced-ssr.mdModified
View file
@@ -475,6 +475,8 @@
​
> 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.
​
+> While React hydrates a component, `useQuery`, `useInfiniteQuery` and `useQueries` render a query that `hydrate` created from the state it was hydrated with, so the first client render matches the server markup. This holds even if the query changes in between, for example because its streamed Promise resolves or another component refetches it. A query that was pending when it was dehydrated therefore hydrates in the `pending` status and shows its data right after hydration. If you want the data in the server markup, use `useSuspenseQuery`. This does not cover queries that `hydrate` did not create, and `isStale` is still computed from the current time on each side.
+​
If 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:
​
```tsx
186 additions and 0 deletionspackages/query-core/src/__tests__/queryObserver.test.tsxModified
View file
@@ -4,7 +4,9 @@
QueryClient,
QueryObserver,
defaultQueryFn,
+ dehydrate,
focusManager,
+ hydrate,
keepPreviousData,