TanStackT
TanStack11mo ago
1 reply
primary-violet

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!
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...
Prefetching & Router Integration | TanStack Query React Docs
Was this page helpful?