Skip to content
Source
Sign inSign up
TanStack/query

(v4) Infinite re-render loop with `suspense: true` and `cacheTime: 0` for synchronous fetchers #9583

Send to my agent
Closedsuhdonghwi(GitHub profile, opens in a new tab) opened this issue 1 comment

Describe the bug

When using useQuery with suspense: true (or useSuspenseQuery) in combination with cacheTime: 0 and a synchronous query function, the component enters an infinite re-render loop.

useQuery(
  ['key'],
  () => 42, // synchronous query function that returns immediately
  { suspense: true, cacheTime: 0 }
);

This happens in @tanstack/react-query version 4.24.2 or higher, but below 5.51.23. More specifically, this issue is introduced by this commit and fixed by this commit.

While this issue has been resolved in recent v5 versions, it remains unfixed in recent v4 versions. Since our team is currently using 4.x.x, I would appreciate guidance on whether it would be appropriate to submit a PR that backports a fix like this PR to the 4.x.x branch.

Your minimal, reproducible example

https://stackblitz.com/edit/vitejs-vite-xrytufnd?file=src%2FApp.tsx

Steps to reproduce

  1. Open the StackBlitz MCVE.
  2. Navigate to App.tsx.
  3. Observe that the suspended App component never resolves.
  4. Check the browser DevTools console - you'll see the "Render App" message being printed infinitely, indicating that the App component is stuck in an infinite re-render loop.

Expected behavior

The useQuery hook should not trigger infinite re-renders and the suspense boundary should resolve normally.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

  • OS: macOS
  • Browser: Chrome

Tanstack Query adapter

react-query

TanStack Query version

v4.24.2 or higher, but below v5.51.23

TypeScript version

No response

Additional context

No response

  1. After comparing the suspension-related codes, the two biggest differences between v5 and v4 are as follows.

    In suspense.ts, ensureStaleTime (renamed to ensureSuspenseTimers in v5) in v4 only includes a guard for staleTime, while in v5 it includes guards for both staleTime and gcTime.

    Another difference is that in v4, shouldSuspend determines suspension using willFetch(result, isRestoring), whereas in v5 it relies on result.isPending. However, since v4 does not handle isPending (more specifically, it does not handle thenables),

    I'm not sure if this is intentional, but in v5, when in suspense mode, ensureSuspenseTimers seems to set the minimum gcTime to 1000 (even if you explicitly set it to less than 1000). Therefore, perhaps, the simplest solution without major structural changes is to add a guard for cacheTime to ensureStaleTime.

  2. manudeli(GitHub profile, opens in a new tab) unassignedsuhdonghwi

Sign in to join this conversation.