Scroll to top on route change with react router

This is a simple method to scroll page to top on route changes. here we are using useEffect to run scrolling function on every path change.

Include this snippet in your App.js.

import { Route, Routes, useLocation } from "react-router-dom";

function App() {
  const { pathname } = useLocation();

  useEffect(() => {
      top: 0,
      left: 0,
      behavior: "instant", // Optional param, you can use "smooth" also.
  }, [pathname]);

export default App;