Maria Jeysingh Anbu
Maria Jeysingh Anbu

Reputation: 3312

React | How to detect Page Refresh (F5)

I'm using React js. I need to detect page refresh. When user hits refresh icon or press F5, I need to find out the event.

I tried with stackoverflow post by using javascript functions

I used javascript function beforeunload still no luck.

onUnload(event) { 
  alert('page Refreshed')
}

componentDidMount() {
  window.addEventListener("beforeunload", this.onUnload)
}

componentWillUnmount() {
   window.removeEventListener("beforeunload", this.onUnload)
}

here I have full code on stackblitz

Upvotes: 58

Views: 170462

Answers (7)

Conor
Conor

Reputation: 109

'navigation' is deprecated, instead, add this to the constructor:

const navigationEntries = window.performance.getEntriesByType('navigation');
if (navigationEntries.length > 0 && navigationEntries[0].type === 'reload') {
 console.log("Page was reloaded");
}

Make sure to wrap it in the useEffect(). The reason for using useEffect in this case is to ensure that the code runs at the appropriate time during the component lifecycle.

When you place the code directly inside the function body without useEffect, it will be executed whenever the component function is called, which could lead to unexpected behavior.

By using useEffect with an empty dependency array ([]), you ensure that the code runs only once, after the initial render of the component. This approach is generally preferred when you want to perform initialization tasks or set up event listeners in a React component.

function MyComponent(){

   useEffect(() => {
     const navigationEntries = window.performance.getEntriesByType('navigation');
     if (navigationEntries.length > 0 && navigationEntries[0].type === 'reload') {
       console.log("Page was reloaded");
     }
   }, []);

}

export default MyComponent;

Upvotes: 2

Michael Harley
Michael Harley

Reputation: 1058

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;
}

Upvotes: 21

pradeepradyumna
pradeepradyumna

Reputation: 1072

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 = "";
  };

Upvotes: 38

Nitesh Malviya
Nitesh Malviya

Reputation: 840

If you are using either REDUX or CONTEXT API then its quite easy. You can check the REDUX or CONTEXT state variables. When the user refreshes the page it reset the CONTEXT or REDUX state and you have to set them manually again. So if they are not set or equal to the initial value which you have given then you can assume that the page is refreshed.

Upvotes: 7

Rvach.Flyver
Rvach.Flyver

Reputation: 304

Unfortunately currently accepted answer cannot be more considered as acceptable since performance.navigation.type is deprecated

The newest API for that is experimental ATM. As a workaround I can only suggest to save some value in redux (or whatever you use) store to indicate state after reload and on first route change update it to indicate that route was changed not because of refresh.

Upvotes: 12

Abdellatif Derbel
Abdellatif Derbel

Reputation: 689

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.

Upvotes: 28

Will
Will

Reputation: 782

Your code seems to be working just fine, your alert won't work because you aren't stopping the refresh. If you console.log('hello') the output is shown.

UPDATE ---

This should stop the user refreshing but it depends on what you want to happen.

componentDidMount() {
    window.onbeforeunload = function() {
        this.onUnload();
        return "";
    }.bind(this);
}

Upvotes: 10

Related Questions