A React Hook you can add to your Route component. Using useLayoutEffect
instead of custom listeners.
import React, { useLayoutEffect } from 'react';
import { Switch, Route, useLocation } from 'react-router-dom';
export default function Routes() {
const location = useLocation();
// Scroll to top if path changes
useLayoutEffect(() => {
window.scrollTo(0, 0);
}, [location.pathname]);
return (
<Switch>
<Route exact path="/">
</Route>
</Switch>
);
}
Update: Updated to use useLayoutEffect
instead of useEffect
, for less visual jank. Roughly this translates to:
useEffect
: render components -> paint to screen -> scroll to top (run effect)useLayoutEffect
: render components -> scroll to top (run effect) -> paint to screenDepending on if you're loading data (think spinners) or if you have page transition animations, useEffect
may work better for you.