Understanding the Problem
When building React applications, especially Single Page Applications (SPAs) using React Router, you might expect the page to scroll to the top automatically when navigating to a new route or after re-rendering a component. But sometimes it doesn’t scroll at all, the user stays at the bottom or middle of the page, even after navigation.
Example:
You navigate from /products to /about, and even though it’s a new page, the scroll stays at the bottom of the screen.
Why This Happens
- React doesn’t refresh the page like traditional websites. It updates only the components.
- Using window.scrollTo(0, 0) immediately after render may not work because the DOM might not be fully updated.
- React batches DOM updates if your scroll logic happens before React finishes rendering, it won’t take effect.
- Navigating with react-router-dom doesn’t automatically reset scroll position.
Real-World Fix: Scroll to Top After Navigation
You need a component that listens for route changes and scrolls to the top after the DOM is ready.
Solution Code: ScrollToTop.js
// ScrollToTop.jsimport { useEffect } from “react”;
import { useLocation } from “react-router-dom”;
const ScrollToTop = () => {
const { pathname } = useLocation();
useEffect(() => {
// Scroll after route change and render
const timeout = setTimeout(() => {
window.scrollTo({ top: 0, behavior: “smooth” });
}, 0);
// Clean up timeout
return () => clearTimeout(timeout);
}, [pathname]);
return null;
};
export default ScrollToTop;
Also Read: How to Convert HTML Website to ReactJS?
How to Use It in Your App
Make sure you include <ScrollToTop /> inside your main layout component, usually above the <Routes> block:
import { BrowserRouter as Router, Routes, Route } from “react-router-dom”;import ScrollToTop from “./ScrollToTop”;
function App() {
return (
<Router>
<ScrollToTop />
<Routes>
<Route path=”/” element={<Home />} />
<Route path=”/about” element={<About />} />
{/* Add your other routes */}
</Routes>
</Router>
);
}
Bonus Tip: Use behavior: “smooth” for better UX
If you want a smooth transition (not an instant jump), make sure you use:
Summary
- React SPA doesn’t auto-scroll when navigating.
- You must manually handle it using a custom scroll component.
- Delay the scroll until after route and DOM updates.
- Use useLocation from react-router-dom and useEffect.