when gcTime is zero, it make hydration fail warning #6427
Send to my agentDescribe the bug#
When gcTime is zero in app router, it make hydration failed. If you use page router, it is not happen.
const [queryClient] = React.useState(() => {
return new QueryClient({
defaultOptions: {
queries: {
staleTime: 5 * 1000,
gcTime: 0, // it make hydration failed.
}
}
})
}
);
return (
<RecoilRoot>
<QueryClientProvider client={queryClient}>
{children}
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</RecoilRoot>
)
Your minimal, reproducible example#
https://github.com/MOONLEE/react-query-hydration-fail.git
Steps to reproduce#
- download git repo (https://github.com/MOONLEE/react-query-hydration-fail.git)
- yarn run install
- yarn run dev
- refresh localhost:3000 in web browser
Expected behavior#
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
- OS : Mac
- Browser : chrome (19.0.6045.159)
- @tanstack/react-query : 5.7.2
- nextjs: 4.0.1
- node: 18.18.2
Tanstack Query adapter#
None
TanStack Query version#
5.7.2
TypeScript version#
5.2.2
Additional context#
No response
TkDodo added labelsneeds-info
I tested it using MacBook Pro at home, it usually work fine. but hydration failed sometimes occurred.
work fine in codesandbox
hydration failed occurred in codesandbox
hydration failed occurred in local env
I don’t know how gcTime is work. I think that hydration failed may occur depending on the network or next.js server environment. In the first testing environment, I used a company computer (MacBook Air). the company network is slower than my home network. hydration failed occurred many times on company computer
I solved this issue as below
const [queryClient] = React.useState(() => { return new QueryClient({ defaultOptions: { queries: { staleTime: 5 * 1000, gcTime: 2 * 1000, } } }) } ); return ( <RecoilRoot> <QueryClientProvider client={queryClient}> {children} <ReactQueryDevtools initialIsOpen={false} /> </QueryClientProvider> </RecoilRoot> )I think gcTime should not be zero in SSR environment and need a notice on react query document. otherwise, need some gcTime option for first time load.
I think what could happen is that our HydrationBoundary puts data into the cache, but it's cleared up immediately with
gcTime: 0because there is no active observer yet, becauseuseQuerywasn't rendered yet. Then, whenuseQueryrenders, it doesn't see the server data, yielding a mismatch.@Ephem is that about right?
If so, I agree, we should add this somewhere to the docs that
gcTime: 0is likely not a good idea in this setup.Sounds right! I'm sure there's an argument to be made that we should artificially keep data around more than
gcTimein these scenarios where we know it's likely data will be used soon, but, I feel that's unnecessary complexity in the library.I agree documenting this is the right approach!
TkDodo removed labelsneeds-info
TkDodo added labelsdocumentation
Is this available to pickup still?
yep, no one's actively working on this I think
Thoughts on where in the docs this info should go? I was thinking under the migrating to v5 page, where the
gcTimeis explicitly called out. But I think your input would be good too.No, this was just a rename. cacheTime in v4 likely has the same problem
Ended up adding the documentation to the important defaults page, figured that was the best spot for it.
Pull request is good to go!
TkDodo closed this
Hi, @TkDodo
Thanks for clarifying earlier that
gcTime: 0can lead to hydration issues because data might be collected before auseQueryobserver attaches. I have a follow-up question about how the GC timer actually works internally.In our application (React, not Next.js), we rely heavily on
gcTime: 0because we want queries to be removed as soon as no components are using them. This has worked really well for us in most cases, so we use it as our default setup. Since our app is very data-heavy, we prefer unused data to be cleared immediately to avoid bloating browser memory.Another reason is that whenever users switch pages/routes/other cases, we prefer to always refresh the latest data. Using an arbitrary cache time can’t satisfy this requirement reliably, and manually clearing the cache in every case adds unnecessary complexity. By defaulting to gcTime: 0, the app becomes more predictable: it’s either idle with no data, or actively fetching the latest data.
We also use a pattern like this:
export function useQueryObserver(keys: QueryKey[]) { useQueries({ queries: keys.map((queryKey) => ({ queryKey, enabled: false, })), }); }We place this hook at the very top level to create only observers, and then trigger the actual fetch with
queryClient.fetchQueryin response to a button click.My question is:
TopLevelComponent: userIds = useIdsFromStore() useQueryObserver(userIds) InternalComponent: useSuspenseQueries(userIds) ButtonClick: const newIds = [xxxx] result = await fetchQuery(newIds) if success -> updateIds(newIds)At the point where I call
fetchQuery, can I be 100% sure that the query will not be garbage-collected immediately (even withgcTime: 0), given that the new IDs are not yet reflected in the observers?I understand that GC only happens when there are no observers. What I’m unclear about is the timing:
- Does
fetchQuerymark the query as inactive immediately and create a GC timer right away? - Or, since the timer is asynchronous, does it wait until the next render/commit cycle, at which point the GC timer might be cancelled if an observer attaches?
I’ve also noticed that newly fetched IDs show a
gcTimeof1s, which I assume is caused byuseSuspenseQueryincreasing it internally.From my testing it seems safe, because queries are not removed when a top-level observer exists. But I couldn’t find documentation explaining exactly when the GC timer is started and how it interacts with React’s render/commit phases.
I realize this might be considered an internal detail and not part of the public API, but I’d like to confirm whether it’s safe to rely on this pattern (using
useQueryonly to create observers, combined withgcTime: 0for immediate cleanup) in production.Thanks!
- Does
Does fetchQuery mark the query as inactive immediately and create a GC timer right away?
yes, this happens here:
it does schedule a
setTimeout(0), then it runs the gc process, which checks for observers.It's very helpful. Thanks for the confirmation!
Sign in to join this conversation.
I opened the reproduction in codesandbox and it works fine:
https://codesandbox.io/p/github/MOONLEE/react-query-hydration-fail/main