Skip to content
Source
Sign inSign up
TanStack/query

Hydration error using loading state of useQuery when prefetching #9399

OpenIcestonks(GitHub profile, opens in a new tab) opened this issue 20 comments

Describe the bug

If you prefetch data on the server and then use useQuery with isLoading on the client, it can lead to a hydration error.

Your minimal, reproducible example

https://stackblitz.com/~/github.com/Icestonks/react-query-trpc-test

Steps to reproduce

  1. Prefetch something on the server
  2. Hydrate it to the client
  3. Use useQuery in the client, and have a loading fallback with isLoading.

Then there should come a hydration error.

Expected behavior

When first building and starting the project, we should see an hydration error. The error can also come at other times, but that's the most reliable way, to get the error to occur.

How often does this bug happen?

Sometimes

Screenshots or Videos

Image

Platform

  • OS: Windows
  • Browser: Google Chrome
  • Browser version: 138.0.7204.100

Tanstack Query adapter

react-query

TanStack Query version

5.82.0

TypeScript version

5.8.3

Additional context

Initially, the issue was thought to be related to tRPC, so there has been some discussion about the error over there: https://github.com/trpc/trpc/issues/6740

Would highly recommend reading some of the comments from that issue. Could maybe also give some more context.

  1. TkDodocommented

    @Ephem this seems to be related to tryResolveSync that was recently added. See the linked trpc issue for more info please.

  2. Yeah, I’m pretty positive that’s the cause. 😞 Suspense kind of acts like a synchronising factor so the SSR pass and hydration has the same status for the promise, but when Suspense is not used things clearly fail.

    I need to think some more on it, but my first naive idea for a fix is treating all useQuery as pending during SSR+hydration if that query was hydrated via a promise (which I think was the case for all queries like this before tryResolveSync, which instead was a problem with Suspense).

    This might be the time when we’ll want to implement getServerSnapshot in uSES. 🤔 That would have pending but the getSnapshot would have success and React would patch things up correctly.

  3. TkDodocommented

    This might be the time when we’ll want to implement getServerSnapshot in uSES

    we already have an issue for this for quite some time 😅

  4. It’s been on my list forever but this is the first time I’ve seen an issue related to it so it hasn’t had a very high prio in my mind. I’m sure we’ve has the occasional rare hard to catch issue stemming from it not being implemented before this though. 🤷

  5. Icestonks(GitHub profile, opens in a new tab)commented

    Hey @Ephem, do you think this is something that's going to be solved in the near future? Or should I just wait with prefetching, until the issue is fixed.

  6. I'm currently on vacation so it might take a bit longer, but this is definitely at the top of my OSS list of things to fix.

  7. joseph0926(GitHub profile, opens in a new tab)commented

    I briefly looked into the issue. It’s really interesting…

    I added a few debugging logs to the reporter’s code and checked the results.

    "use client";
    
    import { useQuery, useQueryClient } from "@tanstack/react-query";
    import { getAmountOfUsers } from "./fetcher";
    import { useEffect, useState } from "react";
    
    const PageClient = ({}) => {
      console.log("=== PageClient Render START ===");
    
      const queryClient = useQueryClient();
      const cache = queryClient.getQueryCache().find({
        queryKey: ["users", "amount"],
      });
    
      console.log("!!! Cache:", {
        status: cache?.state.status,
        data: cache?.state.data,
        promise: cache?.promise,
        promiseType: typeof cache?.promise,
      });
    
      console.log("@@@ Before useQuery:", {
        cacheExists: !!cache,
        cacheState: cache?.state.status,
        cacheData: cache?.state.data,
      });
    
      const query = useQuery(getAmountOfUsers());
    
      console.log("### After useQuery:", {
        isLoading: query.isLoading,
        data: query.data,
        fetchStatus: query.fetchStatus,
      });
    
      console.log("=== PageClient Render END ===");
    
      return (
        <div>
          Amount of users:{" "}
          {query.isLoading ? <em>Loading...</em> : query.data?.amount}
        </div>
      );
    };
    
    export default PageClient;

    I naturally expected that since the server prefetches and hydrates before sending to the client, if the server’s data is undefined, the client would also have undefined, and if the server has data, the client would have it as well.

    But the results were as follows

    // client
    === PageClient Render START ===
    page-client.tsx:15 !!! Cache: {status: 'success', data: {…}, promise: Promise, promiseType: 'object'}data: {amount: 12}promise: Promise {<fulfilled>: {…}, status: 'fulfilled', value: {…}}promiseType: "object"status: "success"[[Prototype]]: Object
    page-client.tsx:22 @@@ Before useQuery: {cacheExists: true, cacheState: 'success', cacheData: {…}}cacheData: {amount: 12}cacheExists: truecacheState: "success"[[Prototype]]: Object
    page-client.tsx:30 ### After useQuery: {isLoading: false, data: {…}, fetchStatus: 'fetching'}data: {amount: 12}fetchStatus: "fetching"isLoading: false[[Prototype]]: Object
    page-client.tsx:36 === PageClient Render END ===
    
    // server
    !!! Cache: {
      status: 'pending',
      data: undefined,
      promise: Promise {}
      promiseType: 'object'
    }
    
    @@@ Before useQuery: { cacheExists: true, cacheState: 'pending', cacheData: undefined }
    ### After useQuery: { isLoading: true, data: undefined, fetchStatus: 'fetching' }
    === PageClient Render END ===

    Sometimes it was undefined on the server, yet the client had data.

    I thought about why this might be possible.

    Possible hypothesis => // 1. RSC (React Server Component) stage

    • Render Layout
    • Run page.tsx (server component) → getServerQueryClient() creates QueryClient A → prefetchQuery() runs (queryFn execution "1") → dehydrate(QueryClient A) = serialize data

    // 2. SSR (Server Side Rendering) stage

    • ClientProvider runs → createQueryClient() creates QueryClient B (new, empty cache!)
    • Render PageClient (uses QueryClient B) → Cache is empty → useQuery starts fetch (queryFn execution "2") → status: 'pending', isLoading: true → HTML: <em>Loading...</em>

    // 3. RSC payload generation (ref: https://nextjs.org/docs/app/getting-started/server-and-client-components#on-the-client-first-load)

    • Next.js injects the result of queryFn 2 into the RSC payload → e.g., {"amount":14} This is what I actually observed (you can find this injection in the Network tab > search for amount under localhost):
            <script>
                self.__next_f.push([1, "64:I[\"[project]/node_modules/.pnpm/next@15.4.6_react-dom@19.1.0_react@19.1.0__react@19.1.0/node_modules/next/dist/lib/metadata/generate/icon-mark.js [app-client] (ecmascript)\",[\"/_next/static/chunks/4787e_next_dist_c67751b4._.js\",\"/_next/static/chunks/src_app_favicon_ico_mjs_4ae240c2._.js\"],\"IconMark\"]\n60:[]\n61:[]\n62:[[\"Array.map\",\"\",0,0,0,0,false]]\n63:[]\n3e:{\"metadata\":[[\"$\",\"title\",\"0\",{\"children\":\"Create Next App\"},\"$3b\",\"$60\",0],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Generated by create next app\"},\"$3b\",\"$61\",0],[\"$\",\"link\",\"2\",{\"rel\":\"icon\",\"href\":\"/favicon.ico?favicon.45db1c09.ico\",\"sizes\":\"256x256\",\"type\":\"image/x-icon\"},\"$3b\",\"$62\",0],[\"$\",\"$L64\",\"3\",{},\"$3b\",\"$63\",0]],\"error\":null,\"digest\":\"$undefined\"}\n52:\"$3e:metadata\"\n59:{\"amount\":12}\n"])
            </script>
    Image

    Then the client state becomes // 1. Initial state

    • ClientProvider: creates QueryClient C (new)
    • HydrationBoundary: receives the dehydrated state from QueryClient A

    // 2. During hydration

    • In HydrationBoundary’s useMemo → Finds new queries → hydrates immediately → Creates a Promise-like object → Fills it with data from the RSC payload

    // 3. React Query v5 tryResolveSync

    • Detects an already resolved Promise-like object
    • Extracts data synchronously!
    • status: 'success', data: { amount: 14 }

    // 4. First render

    • isLoading: false
    • DOM shows "14"
    • React: HTML mismatch! (<em>Loading...</em> vs "14")

    In summary, the core points seem to be

    1. Multiple QueryClient instances are created independently, fragmenting state across them.
    2. There’s a collision (or unintended interaction) between the RSC payload and React Query’s tryResolveSync behavior.
  8. Ephem(GitHub profile, opens in a new tab)commented

    @joseph0926 Your hypothesis is full of misconceptions and is not at all what is happening. I wont go through it all, but:

    • With or without hydration, useQuery does not run during SSR
    • The dehydrated state comes from the RSC pass, not the SSR pass
  9. I think https://github.com/TanStack/query/issues/9642 might be related. I found it easier to start debugging there and posted a little update what I think might be going on. Not 100% sure this one has the exact same mechanism, but I'll try to verify everything when I can.

  10. Hi, I think I am experiencing this exact issue, where a prefetch on the server first SSRs a "loading" state because of query.isLoading. Then, at time of hydration the data is already available and renders the new tree with the correct loaded state, causing a hydration mismatch. Has there been any progress on this? Any workarounds until this is fixed?

  11. Hi, I wanted to know if a solution/work around for this was found.

  12. I'm still facing this hydration error whenever the prefetch call on the server resolves before the first client render, any workarounds for this issue?

  13. I think #9642 might be related. I found it easier to start debugging there and posted a little update what I think might be going on. Not 100% sure this one has the exact same mechanism, but I'll try to verify everything when I can.

    • #9642 has been fixed, can we please double-check if this issue is fixed by this too?
  14. ousamabenyounes(GitHub profile, opens in a new tab)commented

    Verified on main (which contains #10444 / react-query@5.100.1+): the hydration mismatch in this issue is not fixed by #10444.

    Reproduction (added locally to packages/react-query/src/__tests__/ssr-hydration.test.tsx):

    it('should not mismatch on queries prefetched without await that resolve between SSR and client hydration', async () => {
      const consoleMock = vi.spyOn(console, 'error').mockImplementation(() => undefined)
      const key = queryKey()
    
      function SuccessComponent() {
        const result = useQuery({
          queryKey: key,
          queryFn: () => Promise.resolve('success!'),
        })
        return <PrintStateComponent componentName="SuccessComponent" result={result} />
      }
    
      // -- Server --
      setIsServer(true)
      const prefetchClient = new QueryClient({
        defaultOptions: { dehydrate: { shouldDehydrateQuery: () => true } },
      })
      let resolvePrefetch: ((v: unknown) => void) | undefined
      const prefetchPromise = new Promise((res) => { resolvePrefetch = res })
      void prefetchClient.prefetchQuery({ queryKey: key, queryFn: () => prefetchPromise })
    
      const dehydrated = dehydrate(prefetchClient)
      expect(dehydrated.queries[0]?.state.status).toBe('pending')
    
      const renderClient = new QueryClient()
      hydrate(renderClient, dehydrated)
      const markup = ReactDOMServer.renderToString(
        <QueryClientProvider client={renderClient}><SuccessComponent /></QueryClientProvider>,
      )
      renderClient.clear()
      setIsServer(false)
      expect(markup).toBe('SuccessComponent - status:pending fetching:true data:undefined')
    
      // Promise resolves *between* SSR and client hydration (streamed value arrives).
      resolvePrefetch?.('success!')
      const promiseRef = dehydrated.queries[0]?.promise
      if (promiseRef) {
        // Synchronously-resolvable thenable, mirroring a streamed React promise.
        // @ts-expect-error
        promiseRef.then = (cb) => { cb?.('success!'); return promiseRef }
      }
    
      // -- Client --
      const el = document.createElement('div'); el.innerHTML = markup
      const queryClient = new QueryClient()
      hydrate(queryClient, dehydrated)
      ReactHydrate(
        <QueryClientProvider client={queryClient}><SuccessComponent /></QueryClientProvider>,
        el,
      )
      expect(consoleMock).toHaveBeenCalledTimes(0) // FAILS
    })

    React reports:

    Hydration failed because the server rendered text didn't match the client.
    + SuccessComponent - status:success fetching:true data:success!
    - SuccessComponent - status:pending fetching:true data:undefined

    Why #10444 doesn't cover this:

    #10444 / #9642 was about the in-cache transition flicker (success → fetching → success) when a resolved promise was hydrated. That's a single-render concern.

    #9399 is a different concern: the server render of the <HydrationBoundary> subtree calls hydrate() while the streamed promise is still pending — tryResolveSync returns undefined and the SSR HTML is committed in the pending state. By the time the client calls hydrate(), the streamed promise has fulfilled, so tryResolveSync returns the data and the very first client render is in the success state. Server snapshot ≠ client snapshot → React hydration mismatch.

    This can't be papered over inside hydrate() alone — both the server and client hydrate() calls receive the same DehydratedState object, but the underlying streamed promise has different resolution timing in each environment, so any deterministic logic in hydrate() will produce divergent results across the two passes.

    The architectural fix is getServerSnapshot in useBaseQuery (tracked in #4690) — pass a third arg to useSyncExternalStore so the SSR pass and the initial client hydration render use the same stable snapshot, then getSnapshot takes over after commit. Per @Ephem's earlier comment in this thread, that was the suggested direction. Confirming here that #10444 alone does not unblock this issue.

    Happy to take a swing at the getServerSnapshot fix in a separate PR if that aligns with how you want to scope it, @TkDodo / @Ephem.

  15. I checked out the original repo @Icestonks posted and updated it to query 5.100.5. I also was running into an issue with another project I had, which I think was the same issue, so I did the same. The issue is still there, as far as I can tell.

    @ousamabenyounes That reply you posted looks like a Claude Code report, is that correct?

  16. ousamabenyounes(GitHub profile, opens in a new tab)commented

    @DogPawHat fair question — yes, I used Claude Code to write the repro and trace tryResolveSync through hydration.ts. I verified the run myself before posting.

    One correction to my previous comment: expect(consoleMock).toHaveBeenCalledTimes(0) does not fail in React 19 — React 19 throws hydration mismatches as uncaught exceptions instead of logging via console.error, so the spy stays at 0. The bug still reproduces (Vitest surfaces it under "Unhandled Errors" with the exact + status:success / - status:pending diff against the SSR markup), but a correct assertion would catch the thrown error or assert the post-hydration DOM matches the SSR markup.

    Confirmed the same mechanism on 5.100.5. The architectural fix is still getServerSnapshot in useBaseQuery (#4690) so the SSR pass and the initial client hydration render share a stable pending snapshot.

  17. My own attempts to one shot this with Codex doesn't make me that confident in an AI fix rn unless @Ephem or @TkDodo was at the wheel. (which is to say I can fix it but looking at the resulting code raised my eyebrows a bit.)

    Cleary, we probably have to properly implement a getServerScreenshot function that returns the same data on both the ssr pass and intial client render, and because the hydration functions are in that query-core package probaby change some combindation of hydration.ts queryObserver.ts, maybe query.ts as well. I don't know where to go from there.

  18. Yeah, this is unfortunately a complex one. I have a pretty good grasp on what we need to do, but it requires some pretty deep changes. To mention just one of many details, note that we are not currently using the value that useSyncExternalStore returns in useBaseQuery, we are using it as a re-render mechanism. So even after the complexity of capturing an immutable server snapshot, transporting it to each query on a context etc, etc, just passing it as getServerSnapshot into useSyncExternalStore isn't enough, we also need to refactor the observers and useBaseQuery.

    Note that this is also how we fix some other bugs, like: https://github.com/TanStack/query/issues/10145

    I did start doing some deeper exploration into what this would look like this weekend, but I don't have anything firm yet.

  19. Been exploring this a few times over the last few weeks and months. One thing I want to know is on the subject of transporting the immutable server snapshot is if an extra react context provider is needed or we somehow intergrate it into the query cache itself

    The extra provider solution would look something like:

    // packages/react-query/src/HydrationContext.ts
    const HydrationSnapshotContext =
      React.createContext<HydrationSnapshotLayer | undefined>(undefined)
    
    export function HydrationBoundary({ state, children, ...props }) {
      const parentSnapshot = React.useContext(HydrationSnapshotContext)
      const snapshot = createSnapshotLayer(parentSnapshot, state, queryClient)
    
      // Existing real-cache hydration logic remains here.
    
      return (
        <HydrationSnapshotContext.Provider value={snapshot}>
          {children}
        </HydrationSnapshotContext.Provider>
      )
    }
  20. DogPawHat linked this to #12697

Sign in to join this conversation.