Scroll Restoration and Optimistic Route Transitions
Scroll Restoration and Optimistic Route Transitions
1. The Scroll Position Bug in SPAs
In traditional server-rendered websites, when a user scrolls halfway down a long catalog page, clicks a link to view a product, and then clicks the browser "Back" button:
- The browser automatically restores the exact scroll position where they left off.
In a naive Single-Page Application:
- Clicking a link navigates to a new view, but the viewport remains scrolled down at the previous position!
- Clicking "Back" sends the user to the top of the catalog page, forcing them to search and scroll all over again!
This jarring UX flaw is solved in modern React Router via Scroll Restoration.
2. Implementing <ScrollRestoration />
In React Router v6 Data Routers (createBrowserRouter), you simply render <ScrollRestoration /> inside your root layout component:
Custom Scroll Keys (Tabs and Query Params)
By default, scroll positions are keyed by the URL pathname. If you have tabs that change query params (?tab=reviews) and want to preserve scroll independently:
3. Optimistic Route Transitions with useNavigation
When users click a link that loads data via a loader, there may be a 150–300ms delay while data fetches across the network.
Without visual feedback, the user wonders: "Did my click register?"
React Router provides the useNavigation() hook to inspect active in-flight transitions:
4. Pending UI Styling with useNavigation
You can even dim the current screen while the next route is loading:
Practice Quiz
<ScrollRestoration /> be rendered in an application?getKey prop on <ScrollRestoration> allow developers to customize?Architecture of Server-Side Rendering vs Client-Side Rendering
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.