skip to Main Content

Is there any way I can detect page reload on react app. I only want to detect when the page is reloaded when user clicks the reload button or shortcut keys to reload the page not when the page changes without reload when using react router.

I tried using beforeunload but it also detects page changes that react router does.

useEffect(() => {
    window.addEventListener("beforeunload", alertUser);
    return () => {
      window.removeEventListener("beforeunload", alertUser);
    };
  }, []);

2

Answers


  1. I think the best way to do this is to use useEffect(() => ...) in your root component (most likely something called App.tsx or App.jsx) this will only fire when the React application is initialized. Furthermore if you want to only let it run some code on reload you can pass a query paramenter like ?reload=true or something in the URL.

    Login or Signup to reply.
  2. You can use the Performance Navigation Timing interface with React/React-Router-Dom to resolve that. Please see my approach below and read more about the Performance Navigation Timing interface.

    import React from "react";
    import { Navigate } from "react-router-dom";
    
    export default function Navigator = () => {
      const {navigate} = useNavigate();
      const navigationCondition = (window.performance.navigation && 
                                window.performance.navigation.type === 1) 
    
      React.useEffect(() => {
        if (navigationCondition) {
          console.log("Reload detected");
          <Navigate to="/where-you-need-to-go" replace={true} />
        } else {
          console.log("No reload");
        }
      },[]);
    
      return <></>;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search