title: Scroll to top on browser back button click react
body: <p>I need to scroll to top every time the url changes in my project (and on page reload).</p>
  <p>Everything is working but I am having a problem with the browser back button. Even if the pathname changes the page doesn't scroll to top as it should, it works on all other cases (page reload and regular link navigation).</p>
  <p>I tried to counter that creating a custom hook just for the back button, but it's not behaving how I want. I also tried a bunch of other things, but nothing seems to work as for the browser back button</p>
  <pre><code>import { useEffect, useState } from &quot;react&quot;;
  import { useLocation } from &quot;react-router-dom&quot;;
  
  const ScrollToTop = () =&gt; {
    const { pathname } = useLocation();
  
    const useBackButton = () =&gt; {
      const [isBack, setIsBack] = useState(false);
      const handleEvent = () =&gt; {
        setIsBack(true);
      };
      useEffect(() =&gt; {
        window.addEventListener(&quot;popstate&quot;, handleEvent);
        return () =&gt; window.removeEventListener(&quot;popstate&quot;, handleEvent);
      });
      return isBack;
    };
  
    const backButton = useBackButton();
    console.log(backButton);
  
    useEffect(() =&gt; {
      window.scrollTo(0, 0);
    }, [pathname, backButton]);
  
    useEffect(() =&gt; {
      window.onbeforeunload = () =&gt; {
        window.scrollTo(0, 0);
      };
    }, []);
  
    return null;
  };
  
  export default ScrollToTop;
  </code></pre>