`prefetchInRender` causes infinite render loop with deferred value if a promise rejects #8249
Send to my agentDescribe 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
birkskyum(GitHub profile, opens in a new tab) added labelspackage: react-query
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).renderCountreaches a few thousand within a couple of seconds.I attempted a few targeted fixes in
packages/query-core/src/queryObserver.ts:- Gating the
recreateThenablebranches increateResultonquery.queryHash === prevQuery.queryHashso 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 forReact.use(query.promise)to suspend on (should not resolve with intermediate data when keys are switched, etc.). - Per-
queryHashthenable cache so off-query renders get a stable thenable. → still loops, becausegetOptimisticResultthen assigns the off-query result into#currentResultviashouldAssignObserverCurrentProperties, sogetCurrentResultflip-flops between the subscribed and off-screen queries on every render anduseSyncExternalStorenotifies on each one. - Skipping that assignment for off-query renders → breaks 17 unrelated tests because the
placeholderData/ deep-clone path relies on#currentResulttracking the most recently rendered options.
The pattern in each attempt is the same: any local fix in
queryObserver.tseither re-introduces the loop, or shows stale data on a normalqueryKeychange, or breaksplaceholderDatasemantics. The flip-flop is intrinsic to runninggetOptimisticResultwith a differentqueryHashper render against a single shared#currentResult/#currentThenablesnapshot consumed byuseSyncExternalStore.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-corepatch 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.- Gating the
experimental_prefetchInRenderwill be removed, sorry.TkDodo closed this
Sign in to join this conversation.
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