Interview frequency: …
Short answer
Use React Router Data APIs' built-in <ScrollRestoration /> component or a useEffect that observes pathname changes and calls window.scrollTo(0, 0).
Explanation
In SPAs, the browser may not automatically reset the Scroll position after a route change, leaving users halfway down the new page. React Router's ScrollRestoration recreates normal browser behavior and accurately saves each page's scroll position in history.
Code example
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo({ top: 0, left: 0, behavior: 'instant' });
}, [pathname]);
return null;
}Common mistakes
- Using behavior: "smooth" for rapid navigation, causing confusing movement while pages load.