Tanstack Query + Next.js router intergration.
Hello! This might be a silly question, but I'm having a hard time figuring this out with router integration.
I’d like to invalidate or remove queries during route navigation while preserving the cache for browser history-back navigation (e.g., for scroll restoration).
Of course, I could achieve this by prefetching and invalidating queries in every event handler (onClick={() => invalidate/remove}), but I'm looking for a more elegant and cleaner approach using router loaders.
For example, the tanstack query official guide below is fantastic, but it doesn't explain how to handle cache behavior specifically for browser history-back navigation:
(https://tanstack.com/query/latest/docs/framework/react/guides/prefetching#router-integration)
I'm wondering how I can control cache staleness based on the type of page navigation.
Is this possible with an integration for the Next.js Page Router, or is there a better workaround?
Thanks!
Prefetching & Router Integration | TanStack Query React Docs
When you know or suspect that a certain piece of data will be needed, you can use prefetching to populate the cache with that data ahead of time, leading to a faster experience. There are a few differ...
1 Reply
funny-blue•10mo ago
You shouldn't quite have to invalidate on router navigation. Per https://tanstack.com/query/latest/docs/framework/react/guides/important-defaults querys will refresh when remounted. As for the pages router intergration, It boils down to prefetching inside gSSP and passing it down via hydration. gSSP is run on visits via links and router calls, but per https://nextjs.org/docs/pages/building-your-application/data-fetching/get-server-side-props I can't see anything about the nav buttons. I think app router rscs and tanstack/rr loaders will run on browser back navigation.
Important Defaults | TanStack Query React Docs
Out of the box, TanStack Query is configured with aggressive but sane defaults. Sometimes these defaults can catch new users off guard or make learning/debugging difficult if they are unknown by the u...
Data Fetching: getServerSideProps | Next.js
Fetch data on each request with
getServerSideProps.