Course contentsShow
← React
Lesson 737 of 2,39619. useRefFree lesson

Scroll to Top on Navigation

Combine useEffect with window.scrollTo(0, 0) or a ref to reset scroll position on route changes.

Scroll to Top on Navigation

You'll learn how to automatically reset scroll position to the top of the page whenever users navigate between routes in your React app.

The Problem

When navigating between pages in a single-page application (SPA), React doesn't automatically scroll to the top like traditional multi-page websites do. Users might navigate from the middle of one long page to another page, but remain scrolled down—a confusing experience that makes it seem like the new page has no content.

The Solution: useEffect + window.scrollTo

Since navigation is a side effect that happens after a route change renders, useEffect is the perfect tool. Combine it with window.scrollTo(0, 0) to reset scroll position whenever the route changes:

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

function ScrollToTop() {
  const location = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [location.pathname]);

  return null;
}

Add this component near the top of your app structure (inside your router), and it will trigger on every route change.

Alternative: Using a Ref

You can also use a ref attached to a container element and scroll it instead:

const containerRef = useRef(null);

useEffect(() => {
  containerRef.current?.scrollTo(0, 0);
}, [location.pathname]);

This approach is useful when you have a scrollable container rather than scrolling the entire window.

Key Takeaway: Use useEffect with window.scrollTo(0, 0) (or a ref's scrollTo method) and watch location.pathname in the dependency array to automatically scroll to top on navigation—a simple quality-of-life improvement that makes your SPA feel more like a traditional website.