Hydration error thrown when using `PersistQueryClientProvider` and `Suspense`
Les mainteneurs répondent en général sous 1 jour
Personne n'a encore pris cette issue.
Évaluation
- Difficulté
- 4/5
- Temps estimé
- 3-5 jours
- Accessibilité débutants
- 35/100
- Type d'issue
- Bug
- Clarté
- Plutôt claire
- Activité
- À l'abandon
- Stack technique
- next.js, react, typescript
- Domaine
- frontend
Piste de recherche
Commencez par exécuter localement la reproduction minimale liée, puis comparez le comportement avec et sans le chargement de loading.tsx, ainsi qu’avec SomeData enveloppé dans Suspense dans layout.tsx. Suivez PersistQueryClientProvider, createAsyncStoragePersister et useIsRestoring afin de déterminer l’état pending attendu pendant la restauration ; le travail est terminé lorsque les données mises en cache ne provoquent plus de mismatch d’hydratation dans la reproduction.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Description
Describe the bug
My real use-case:
- A modern Next.js app with authentication
- The authentication is completely offloaded to the browser
- The server does not have an auth token (a JWT, but knows if the user is potentially logged in if a refresh token is present)
- When logged in, the server returns loaders for the UI parts that are user specific
- The browser replaces them with actual data
- The browser caches data in
localStorageusingPersistQueryClientProviderandcreateAsyncStoragePersister
However, the example attached isn't that complex, it's a minimal example which reproduces the issue.
For the case above, the browser might have instant access to cached authenticated data. For instance, let's say we want to print the user's email address. The user has logged in earlier and this data is cached in localStorage, and as mentioned above, the server doesn't have this data. This is what happens:
- Both the server and the client call the same
useQuery. - Server: Since this data is not prefetched, the
statusis alwayspendingin the server, and a loader is returned - Client: The client hydrates, but it instantly has access to the cached
userand prints the email address
There is a mismatch here since the server rendered loading, while the client the email address. This case seems to be handled well when a component is not in a Suspense, but when it is, the last step will throw hydration errors (whether that's a loading.tsx or just a manual <Suspense>).
I have added some logs, and here is what I get:
Component not in Suspense:
not in suspense {status: 'pending', data: undefined, isRestoring: true}
not in suspense {status: 'success', data: {…}, isRestoring: false}
Component in Suspense:
in suspense {status: 'success', data: {…}, isRestoring: true}
in suspense {status: 'success', data: {…}, isRestoring: false}
When the component within a Suspense is rendering for the first time, the status is success, which renders data differently from the server, which I believe is the cause of the hydration error.
From the repo, here is part of the code that handles the loading UI:
const { data, status } = useSomeData();
if (status === "pending") {
return <main>loading</main>;
}
The workaround is:
const { data, status } = useSomeData();
const isRestoring = useIsRestoring();
if (status === "pending" || isRestoring) {
return <main>loading</main>;
}
That works, and does not throw hydration errors. But I feel that is bad DX, and I would prefer not to have to do that for every query call.
Your minimal, reproducible example
https://github.com/ali-idrizi/react-query-suspense-hydration-error
Steps to reproduce
Unfortunately it's a bit difficult to test this on CodeSandbox, as it doesn't seems to throw any hydration errors for some reason. Even rendering a simple {typeof window === 'undefined' ? 'x' : 'y'} does not throw an error for me. I have attached a repo instead, and you might have to run this locally, but there is also a video recording below.
To see the error, you will have to load the page once, so the data gets cached in the browser, afterwards the issue occurs on every subsequent reload.
You can try:
- Remove the
loading.tsxfile and notice no hydration errors thrown - Wrap the
SomeDatacomponent inlayout.tsxwith aSuspenseand notice the hydration error count increase
Expected behavior
Perhaps keep status as pending while isRestoring === true, similar to when a component is not within a Suspense?
How often does this bug happen?
Every time
Screenshots or Videos
https://github.com/TanStack/query/assets/20397725/4581ed80-60b1-4b36-b2b3-d16136f25bc1
Platform
- Windows 10 (WSL)
- Chrome 119
Tanstack Query adapter
react-query
TanStack Query version
5.12.2
TypeScript version
5.2.2
Additional context
No response
- Langage dominant
- TypeScript
- Étoiles
- 50.6k
- Forks
- 4.2k
- Merge moyen
- 9 h 50 min
- PR mergées (30 j)
- 310
Préparer son environnement
- Aucun Dockerfile ni fichier Docker Compose
- Propose un modèle de pull request
- Lire le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Autres issues de TanStack/query
-
Difficulté 2/5 1-3 heures Accessibilité débutants 78/100
TanStack/query#12466 · 1 commentaire ·
Les mainteneurs répondent en général sous 1 jour
-
solid-query: STRICT_READ_UNTRACKED on Solid 2 — client()/options() read in component body (useMutation, useBaseQuery)Peut-être à nouveau libre @LeonxLJX l’a pris il y a 77 jours, et aucune pull request n’est ouverte. Ouverte
Difficulté 2/5 1-3 heures Accessibilité débutants 84/100
TanStack/query#11358 · 2 commentaires · 1 réaction ·
Les mainteneurs répondent en général sous 1 jour
-
select that throws for placeholderData brings back the selection of data removed by resetQueriesPeut-être pris Une pull request liée à cette issue est ouverte ou déjà fusionnée. Ouverte
Difficulté 3/5 1-2 jours Accessibilité débutants 56/100
Les mainteneurs répondent en général sous 1 jour
-
Render loop since v5.105.2 when placeholderData, or its select result, is not referentially stableOuverte
Difficulté 4/5 3-5 jours Accessibilité débutants 54/100
Les mainteneurs répondent en général sous 1 jour
-
useQueries: stable combine returns a stale result when a query updates before setQueries runsPeut-être pris @sakaintp l’a pris il y a 1 jour. Ouverte
Difficulté 3/5 1-2 jours Accessibilité débutants 62/100
TanStack/query#12626 · 2 commentaires ·
Les mainteneurs répondent en général sous 1 jour
Toutes les issues de TanStack/query
Issues similaires
-
Difficulté 2/5 1-3 heures Accessibilité débutants 78/100
fb55/htmlparser2#2579 ·
Les mainteneurs répondent en général sous 1 jour
-
bug good first issue needs-review
Difficulté 1/5 1-3 heures Accessibilité débutants 83/100
Les mainteneurs répondent en général sous 1 jour
-
Add Module DB RulesOuvertedocumentation public
Difficulté 1/5 1-3 heures Accessibilité débutants 68/100
midnightntwrk/umbradb#65 ·
Les mainteneurs répondent en général sous 2 jours
-
area/channels kind/bug priority/medium
Difficulté 2/5 1-3 heures Accessibilité débutants 78/100
nanocoai/nanoclaw#4501 · 1 commentaire ·
Les mainteneurs répondent en général sous 1 jour
-
Docker images: plain X.Y.Z tag (e.g. 7.2.3) is never updated after the initial release buildOuverteneeds verification
Difficulté 2/5 1-3 heures Accessibilité débutants 74/100
Les mainteneurs répondent en général sous 13 jours