`useSuspenseQuery` do not respect cached data in `persister` #8400
Send to my agentDescribe 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#
- Wait till app is loaded
- Observe: The data is cached in
localStorage - 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
TkDodo added labelshas workaround
TkDodo added labelssuspense
TkDodo closed this
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
useSuspenseQueryones. 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
PersistGateidea is something that could be baked into thePersistQueryClientProvider?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 thePersistGateto getsuspense + persistworking.I agree it should definitely be updated in the docs. Would be great if you could file a PR 🙏
@TkDodo Was not sure which would be the best place to ask, but here seemed relevant 🙏
When using
ReactQueryStreamedHydration, is it possible to avoidSuspensetriggering on page reload? Tried persisting the data tolocalStorageas well as implementing aPersistGateyou've linked to in this issue, but queries keep on triggeringSuspensefallbacks 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
Suspensefallbacks only when there's no data persisted, and on reloads or subsequent visits happening withinstaleTime, 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
queryor at least something that is being considered? Or do you see this as a non-viable approach? Would really love to hear your opinion 🫡@dahaca I would need to see it please :)
@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
localStorageis synchronous, perhaps there's a way to avoid having to use aPersistGate? As I understood from the docs – it helps avoid race conditions, aka queries are firing before hydration, sincePersistQueryClientProvideris async? Yet having your app benullis an absolute no-go imo...The ideal expected flow with the code I've linked to (provided localStorage is not empty) should be:
Server RequestApp renders and queries hydrate from localStorage as they get mountedResponse is streamed from the server to replace potentially stale data
@TkDodo should I be expecting an update on this? 🙏
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
localStoragetocreateAsyncPersisteras well. The differentiation between sync / async is pretty meaningless here.
Sign in to join this conversation.
Thanks for filing, I think I know why that is. The app continues to render in an
unsubscribedstate 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
useSuspenseQuerywould returnundefinedasdataon that render cycle, which is something thatuseSuspenseQueryisn’t supposed to do.datashould 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
PersistGatethat 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
Appisn’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.