HydrationBoundary double fetching on subsequent visits #9610
Send to my agentDescribe the bug#
I used HydrationBoundary in React Router. In loader(), I get the data, dehydrate it, then hydrate the client side query client.
- For the first visit, since it's a new query, it got hydrated in
React.useMemo - For subsequent visits, it will be deferred to
React.useEffect, however, if the cache is stale, query client will refetch beforeuseEffect, 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
In my opinion, this issue seems to be a case where React's rendering order conflicts with React Query's behavior.
The reason HydrationBoundary delays existing queries with useEffect is likely to prevent unexpected UI updates during React's Concurrent rendering. The problem is that this causes a side effect (this issue)
useMemo (during render) → component render → useEffect (after render) During this window, useQuery executes, detects a “stale cache,” and initiates a refetch.
To fix this issue, I believed we needed to prevent unnecessary refetches while maintaining transition safety.
Therefore, I passed a flag indicating “this query is about to be hydrated with fresh data,” instructing the QueryObserver to wait briefly. Of course, since it still runs in useEffect during the transition, safety is maintained.
Sorry for the delay before looking at this, I've had a few busy weeks.
I think your analysis about what is happening is likely correct, but the details are tricky to reason about here. I think the
HydrationBoundaryuseEffectshould always run beforeuseBaseQueryeffects further down the tree, so if we have hydrated something, it should already be in the cache when the next effect runs. However, because these effects happen in the same pass, I suspectuseSyncExternalStorehas not had time to update, which might be an important detail here.I haven't verified the exact behaviour so not sure about the best fix yet, thank you for reporting this!
@Ephem
I have a question. In my view, the processing related to this issue in
HydrationBoundaryinvolves setting thehydrationQueuewithuseMemoand thehydrateoperation withinuseEffect. Meanwhile, inuseBaseQuery, the task of subscribing viauseSyncExternalStoreand determining repatches seems to occur. The problem is that the sequence of operations proceeds as follows1. Setting `hydrationQueue` to `useMemo` -> 2. In `useBaseQuery`, subscribing via `useSyncExternalStore` and determining refetch -> 3. `hydrate` in `useEffect`.This sequence results in two fetches occurring.
This seems to be for safety reasons. https://github.com/TanStack/query/blob/a2151d28e1cc2a484634b93841d08d24ab683886/packages/react-query/src/HydrationBoundary.tsx#L44-L50
So the solution I thought of was
1. useMemo sets a temporary flag saying “Hydration is scheduled from now on” -> 2. useSyncExternalStore checks the flag and says “Hydration is scheduled, so don't refetch” -> 3. useEffect triggers the refetch -> only one fetch should occur...?That was the flow I envisioned. I suspect Next.js also faces this issue, and looking at their code, they seem to solve it using a flag too. Of course, theirs is more complex since it involves streaming as well...
Is there a chance my PR (https://github.com/TanStack/query/pull/9617) could solve this issue?
Translated with DeepL.com (free version)
Hey there I experienced a similar problem in React Router Framework Mode, I found a simple fix though, you can use the client loader to fetch directly on the client and avoid the loader hydration at all you can still use the loader() data via await serverLoader() inside the client loader this avoids that the useQuery will not refetch as it already sees the fetch because we directly fetch on the client not on the server so we avoid hydration at all, however I noticed if you set staletime to something near 0 after the loader / clientLoader loaded the data it will still refetch because the time from clientLoader -) useQuery mount is already stale again so a simple fix is using a default stale time like 1s
sukvvon(GitHub profile, opens in a new tab) linked this to #9968
ostapondo(GitHub profile, opens in a new tab) linked this to #11137
Sign in to join this conversation.
@Ephem could you have a look at this please?