Chapter 32: Scroll Restoration
Core Idea
TanStack Query doesn't implement scroll restoration itself, but it removes the usual SPA culprit — refetch-induced UI resets — by serving cached data synchronously on navigating back, so a router's own scroll restoration (React Router's ScrollRestoration, TanStack Router's, or a custom history-based one) has a stable layout to restore a position against.
Key Concepts
- The SPA regression this addresses: client-side data fetching broke traditional browser scroll restoration because navigating back to a page usually re-triggers a fetch, and the layout shifts (loading state → content) before the browser's saved scroll offset can apply correctly.
- Why it "just works" here: query results are cached and retrievable synchronously on re-render, as long as the query hasn't been garbage-collected (default
gcTime 5 minutes) — so navigating back renders the previous content immediately, with no loading-state layout shift, for regular, paginated, and infinite queries alike.
- Division of responsibility: TanStack Query's job is keeping the data available and stable; the actual scroll-position save/restore mechanics are the router's responsibility.
Key Takeaways
- Don't look for a scroll-restoration API in TanStack Query itself — the fix is indirect, via cache stability, and the actual restoration is done by your router.
- If back-navigation still shows a layout jump, check
gcTime first — a query garbage-collected before the user navigates back will refetch and reintroduce the loading-state flash this chapter describes avoiding.
- Pair this with
placeholderData on any query whose key changes with navigation state, to avoid a flash even when the exact cache entry isn't a hit.
Connects To
- Important Defaults:
gcTime, the setting that determines how long cached data stays available for this to work.
- Placeholder Query Data: complementary technique for avoiding flashes on keys that change with navigation.