Skip to content

HydrationBoundary double fetching on subsequent visits #9610

@CB2Moon

Description

@CB2Moon

Describe the bug

I used HydrationBoundary in React Router. In loader(), I get the data, dehydrate it, then hydrate the client side query client.

  1. For the first visit, since it's a new query, it got hydrated in React.useMemo
  2. For subsequent visits, it will be deferred to React.useEffect, however, if the cache is stale, query client will refetch before useEffect, which makes the server compute the data twice: one in loader, the other in the component

I looked into the source code and found that it's due to refetchOnMount, which is true by default. I think it would be plausible to prevent a refetch if the query in the dehydrated state is fresh.

There are some experiments in the provided code, e.g. initialData from React Query meets React Router, initialData + initialDataUpdatedAt, HydrationBoundary, and my custom hook use-hydrated-query which sets refetchOnMount to false for that query if not explicitly provided during hydration. You may navigate away and back for each experiment and see the log in console to reproduce the issue.

Your minimal, reproducible example

https://stackblitz.com/edit/vitejs-vite-yiggax3s

Steps to reproduce

mentioned in 'Describe the bug'

Expected behavior

If query is fresh from loader(), client side query client should not refetch

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

Any browser

Tanstack Query adapter

react-query

TanStack Query version

v5.85.3

TypeScript version

5.8.3

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions