Hydration error thrown when using `PersistQueryClientProvider` and `Suspense`

Aberta
#6,472 6 comentários 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 1 dia

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
4/5
Tempo estimado
3-5 dias
Facilidade para iniciantes
35/100
Tipo de issue
Bug
Clareza
Razoavelmente clara
Status de atividade
Estagnada
Stack de tecnologia
next.js, react, typescript
Domínio
frontend

Direção de pesquisa

Comece executando localmente a reprodução mínima vinculada e, em seguida, compare o comportamento com e sem o carregamento de loading.tsx e com SomeData envolvido em Suspense em layout.tsx. Rastreie PersistQueryClientProvider, createAsyncStoragePersister e useIsRestoring para determinar o estado pending esperado durante a restauração; o trabalho estará concluído quando os dados armazenados em cache não causarem mais um hydration mismatch na reprodução.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

package: react-query
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 localStorage using PersistQueryClientProvider and createAsyncStoragePersister

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 status is always pending in the server, and a loader is returned
  • Client: The client hydrates, but it instantly has access to the cached user and 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.tsx file and notice no hydration errors thrown
  • Wrap the SomeData component in layout.tsx with a Suspense and 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

Linguagem predominante
TypeScript
Estrelas
50.6k
Forks
4.2k
Merge médio
9h 50min
PRs com merge (30d)
310

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de TanStack/query

Todas as issues de TanStack/query

Issues semelhantes

Mais issues de TypeScript

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.