Skip to content
Source
Sign inSign up
TanStack/query

`prefetchInRender` causes infinite render loop with deferred value if a promise rejects #8249

Send to my agent
Closedali-idrizi(GitHub profile, opens in a new tab) opened this issue 3 comments

Describe the bug

When the query of a deferred component rejects, it falls into an infinite render loop. This is consistent and I have written a test case.

I was waiting to see if this was being caused by https://github.com/TanStack/query/issues/8219, but it appears not. Here's the test:

it.only('should throw error if query fails with deferred value', async () => {
  function MyComponent(props: { promise: Promise<string> }) {
    const data = React.use(props.promise)

    return <>{data}</>
  }

  const key = queryKey()
  let renderCount = 0

  function Page() {
    renderCount++

    const [_count, setCount] = React.useState(0)
    const count = React.useDeferredValue(_count)

    const query = useQuery({
      queryKey: [key, count],
      queryFn: async () => {
        await sleep(1)
        // succeed only on first query
        if (count === 0) {
          return 'test' + count
        }
        throw new Error('Error test')
      },
      retry: false,
    })

    return (
      <React.Suspense fallback="loading..">
        <button onClick={() => setCount((curr) => curr + 1)}>inc</button>
        <MyComponent promise={query.promise} />
      </React.Suspense>
    )
  }

  const rendered = renderWithClient(
    queryClient,
    <ErrorBoundary fallbackRender={() => <div>error boundary</div>}>
      <Page />
    </ErrorBoundary>,
  )

  await waitFor(() => rendered.getByText('loading..'))
  await waitFor(() => rendered.getByText('test0'))

  const consoleMock = vi
    .spyOn(console, 'error')
    .mockImplementation(() => undefined)

  fireEvent.click(rendered.getByText('inc'))

  await waitFor(() => rendered.getByText('error boundary'))

  consoleMock.mockRestore()

  // unsure what the exact render count should be, but it should be less than 10
  // it's 6 without `useDeferredValue`, when test passes
  expect(renderCount).toBeLessThan(10)
})

It currently fails waiting for the error boundary because of the infinite render. If you catch the waitFor throw, you will notice very large values for renderCount:

AssertionError: expected 5828 to be less than 10

The same issue occurs when removing useDeferredValue, and updating the count within a startTransition instead.

Your minimal, reproducible example

Failing test provided

Steps to reproduce

N/A

Expected behavior

N/A

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

OS: Windows 11 Browser: Chrome Version: 129.0

Tanstack Query adapter

react-query

TanStack Query version

06e315c

TypeScript version

No response

Additional context

No response

  1. I ran this test with:

    and it seems to be fixed in that branch, so it’ll implicitly fix this issue as well I guess. @KATT FYI

  2. birkskyum(GitHub profile, opens in a new tab) added labelspackage: react-query

  3. Hi — picked this up via /contribute and wanted to share what I found before opening a PR.

    I reproduced the infinite-render loop on current main (commit 72a15ae4d) with the test case from the original report (useQuery + useDeferredValue + experimental_prefetchInRender + a rejecting query). renderCount reaches a few thousand within a couple of seconds.

    I attempted a few targeted fixes in packages/query-core/src/queryObserver.ts:

    1. Gating the recreateThenable branches in createResult on query.queryHash === prevQuery.queryHash so off-screen renders don't churn #currentThenable. → fixes the loop in the deferred-value test, but breaks 4 existing tests that rely on a key change immediately producing a new pending thenable for React.use(query.promise) to suspend on (should not resolve with intermediate data when keys are switched, etc.).
    2. Per-queryHash thenable cache so off-query renders get a stable thenable. → still loops, because getOptimisticResult then assigns the off-query result into #currentResult via shouldAssignObserverCurrentProperties, so getCurrentResult flip-flops between the subscribed and off-screen queries on every render and useSyncExternalStore notifies on each one.
    3. Skipping that assignment for off-query renders → breaks 17 unrelated tests because the placeholderData / deep-clone path relies on #currentResult tracking the most recently rendered options.

    The pattern in each attempt is the same: any local fix in queryObserver.ts either re-introduces the loop, or shows stale data on a normal queryKey change, or breaks placeholderData semantics. The flip-flop is intrinsic to running getOptimisticResult with a different queryHash per render against a single shared #currentResult/#currentThenable snapshot consumed by useSyncExternalStore.

    Following the discussion on #8434, where @TkDodo concluded (comment):

    we're gonna wait for concurrent stores.

    …this looks like the same root cause and not something a small query-core patch can resolve without an architectural change. Closing out without a PR. Happy to revisit once the React concurrent-stores story lands or if a different direction is preferred.

  4. experimental_prefetchInRender will be removed, sorry.

  5. TkDodo closed this

Sign in to join this conversation.