Skip to content
Source
Sign inSign up
TanStack/query

when gcTime is zero, it make hydration fail warning #6427

Send to my agent
ClosedMOONLEE(GitHub profile, opens in a new tab) opened this issue 12 comments

Describe 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

  1. download git repo (https://github.com/MOONLEE/react-query-hydration-fail.git)
  2. yarn run install
  3. yarn run dev
  4. refresh localhost:3000 in web browser

Expected behavior

img

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

  1. I opened the reproduction in codesandbox and it works fine:

    https://codesandbox.io/p/github/MOONLEE/react-query-hydration-fail/main

  2. TkDodo added labelsneeds-info

  3. I tested it using MacBook Pro at home, it usually work fine. but hydration failed sometimes occurred.

    • work fine in codesandbox success_sandbox_contents success_sandbox_log

    • hydration failed occurred in codesandbox failed_sandbox_contents failed_sandbox_contents

    • hydration failed occurred in local env failed_local_content failed_local_log

    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.

  4. I think what could happen is that our HydrationBoundary puts data into the cache, but it's cleared up immediately with gcTime: 0 because there is no active observer yet, because useQuery wasn't rendered yet. Then, when useQuery renders, 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: 0 is likely not a good idea in this setup.

  5. Sounds right! I'm sure there's an argument to be made that we should artificially keep data around more than gcTime in 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!

  6. TkDodo removed labelsneeds-info

  7. TkDodo added labelsdocumentation

  8. Is this available to pickup still?

  9. yep, no one's actively working on this I think

  10. Thoughts on where in the docs this info should go? I was thinking under the migrating to v5 page, where the gcTime is explicitly called out. But I think your input would be good too.

  11. No, this was just a rename. cacheTime in v4 likely has the same problem

  12. Ended up adding the documentation to the important defaults page, figured that was the best spot for it.

    Pull request is good to go!

  13. TkDodo closed this

  14. Hi, @TkDodo

    Thanks for clarifying earlier that gcTime: 0 can lead to hydration issues because data might be collected before a useQuery observer 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: 0 because 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.fetchQuery in 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 with gcTime: 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 fetchQuery mark 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 gcTime of 1s, which I assume is caused by useSuspenseQuery increasing 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 useQuery only to create observers, combined with gcTime: 0 for immediate cleanup) in production.

    Thanks!

  15. TkDodocommented

    Does fetchQuery mark the query as inactive immediately and create a GC timer right away?

    yes, this happens here:

    https://github.com/TanStack/query/blob/1c8a92167769f322d0206325b98493769afb0961/packages/query-core/src/query.ts#L602-L605

    it does schedule a setTimeout(0), then it runs the gc process, which checks for observers.

  16. It's very helpful. Thanks for the confirmation!

Sign in to join this conversation.