Skip to content
Source
Sign inSign up
TanStack/query

`useSuspenseQuery` do not respect cached data in `persister` #8400

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

Describe the bug

I would like to pre-cache useQuery data, so when the user visits app a second time, the app will show stale data, and refetch in background.

I used persisted with useQuery before it was working as expected, but when I switched to useSuspenseQuery, the cached data is not used anymore.

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      gcTime: 1000 * 60 * 60 * 24 * 7, // 7 days
      staleTime: 0,
    },
  },
});
// ...
function App() {
  useSuspenseQuery({
    queryKey: ['test'],
    queryFn: async () => {
      await sleep(1000);
      return 'ok';
    },
  });
  return <div>App is ready. Data cached. Try to reload</div>;
}

Your minimal, reproducible example

https://stackblitz.com/edit/vitejs-vite-ihky3z?file=index.tsx

Steps to reproduce

  1. Wait till app is loaded
  2. Observe: The data is cached in localStorage
  3. Press refresh button to reload the page

Expected behavior

The loader should not be shown for second time.

How often does this bug happen?

None

Screenshots or Videos

No response

Platform

  • Chrome 131.0.6778.87 (Official Build) (64-bit)

Tanstack Query adapter

react-query

TanStack Query version

5.62.2

TypeScript version

5.7.2

Additional context

No response

  1. Thanks for filing, I think I know why that is. The app continues to render in an unsubscribed state while re-storing from a persisted cache, mainly for SSR reasons.

    In that state, we’re not supposed to fire any fetches, because we aren’t subscribed to the store yet. However, with suspense, we’re throwing promises from the render function directly, so this gets bypassed.

    We could stop that fetch from happening, too, however, then useSuspenseQuery would return undefined as data on that render cycle, which is something that useSuspenseQuery isn’t supposed to do. data should always be defined with it.

    So I think suspense is just not really compatible with restoring data like that. The best workaround I can offer is writing a PersistGate that stops the app from rendering altogether while you’re restoring.

    Here’s a fork that shows this, and it works like you’d expect:

    https://stackblitz.com/edit/vitejs-vite-zxnzxn3p?file=index.tsx

    As App isn’t rendered while the restore takes place, suspense won’t have the chance to fire anything. Then, when data is in the cache, you’ll get cached data served.

  2. TkDodo added labelshas workaround

  3. TkDodo added labelssuspense

  4. TkDodo closed this

  5. This feels like a major footgun to me. I just switched on the persister and spent a while figuring out why half of my hooks don't seem to use it before realizing that it's the useSuspenseQuery ones. Since this behavior is unexpected, could we add some language about this to the persistQueryClient docs (and maybe the useSuspenseQuery docs)?

    But more importantly: we definitely want both suspenses and local storage persistence. In one case of interest, we're fetching app/user config from an API. Since this config has exist before we can call any other API, it's a perfect candidate for a suspense high up in the tree. But, for exactly the same reasons, and because it rarely changes, it's also a perfect candidate for persistence in local storage, to save that round-trip on every refresh. (Especially during development.) How to choose?!? 🤷

    Looking at your example above, I wonder if the PersistGate idea is something that could be baked into the PersistQueryClientProvider?

  6. I wonder if the PersistGate idea is something that could be baked into the PersistQueryClientProvider?

    generally I’d say no, otherwise, this would’ve been the default behaviour. If you have a PersistGate, you can’t have SSR. That’s your decision to make, so you can opt into the PersistGate to get suspense + persist working.

  7. I agree it should definitely be updated in the docs. Would be great if you could file a PR 🙏

  8. @TkDodo Was not sure which would be the best place to ask, but here seemed relevant 🙏

    When using ReactQueryStreamedHydration, is it possible to avoid Suspense triggering on page reload? Tried persisting the data to localStorage as well as implementing a PersistGate you've linked to in this issue, but queries keep on triggering Suspense fallbacks even though they should have data persisted on the first render. Perhaps there's a collision between streamed hydration and local storage hydration?

    Ideally, I'd want to see Suspense fallbacks only when there's no data persisted, and on reloads or subsequent visits happening within staleTime, I'd like the persisted data to be shown as a kind of an optimistic placeholder, waiting to be re-placed with streamed data from requests kicked off on the server.

    Is it something which is possible with query or at least something that is being considered? Or do you see this as a non-viable approach? Would really love to hear your opinion 🫡

  9. @dahaca I would need to see it please :)

  10. @TkDodo Here you go!

    On the dev server the fallback is still there, however when built it's actually barely noticeable (although I'd figure it could depends on the query logic complexity?)

    Since localStorage is synchronous, perhaps there's a way to avoid having to use a PersistGate? As I understood from the docs – it helps avoid race conditions, aka queries are firing before hydration, since PersistQueryClientProvider is async? Yet having your app be null is an absolute no-go imo...

    The ideal expected flow with the code I've linked to (provided localStorage is not empty) should be:

    • Server Request
    • App renders and queries hydrate from localStorage as they get mounted
    • Response is streamed from the server to replace potentially stale data
  11. @TkDodo should I be expecting an update on this? 🙏

  12. sorry, don’t really have the bandwidth to look into this right now.

    Since localStorage is synchronous, perhaps there's a way to avoid having to use a PersistGate?

    restoring is always async even if the store is sync. we might be removing the sync store creation because you can pass localStorage to createAsyncPersister as well. The differentiation between sync / async is pretty meaningless here.

Sign in to join this conversation.