React | How to detect Page Refresh (F5)

It is actually quite straightforward, this will add the default alert whenever you reload your page.

In this answer you will find:

  1. Default usage
  2. Alert with validation

1. Default Usage

Functional Component

useEffect(() => {
    window.onbeforeunload = function() {
        return true;
    };

    return () => {
        window.onbeforeunload = null;
    };
}, []);

Class Component

componentDidMount(){
    window.onbeforeunload = function() {
        return true;
    };
}

componentDidUnmount(){
    window.onbeforeunload = null;
}

2. Alert with validation

You can put validation to only add alert whenever the condition is true.

Functional Component

useEffect(() => {
    if (condition) {
        window.onbeforeunload = function() {
            return true;
        };
    }

    return () => {
        window.onbeforeunload = null;
    };
}, [condition]);

Class Component

componentDidMount(){
    if (condition) {
        window.onbeforeunload = function() {
            return true;
        };
    }
}

componentDidUnmount(){
    window.onbeforeunload = null;
}

If you're using React Hook, UseEffect you can put the below changes in your component. It worked for me

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

Place this in the constructor:

if (window.performance) {
  if (performance.navigation.type == 1) {
    alert( "This page is reloaded" );
  } else {
    alert( "This page is not reloaded");
  }
}

It will work, please see this example on stackblitz.