When user navigates through React js application then decides to click on the browser’s Back button, the URL will change but the content will remain not changed (not show the previous page’s content).

To fix this issue, we need to reload the page. The best way to do that is as following:

useEffect(() => {
    // The following line is a check for Next.js
    if (typeof window === "undefined") return false;
    // A function to handle the event, where the fix code will be
    const handleBackButton = () => {
      history.go(0); // or use history.go() without adding 0
    }
    // Handle back event
    window.addEventListener("popstate", handleBackButton)
    // clearing the event
    return () => {
      window.removeEventListener("popstate", handleBackButton)
    }
  }, [])

The issue then should be fixed and the page will do a soft reload.

Leave a Reply

Your email address will not be published. Required fields are marked *