Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 444
Maria Jeysingh Anbu Avatar asked Apr 25 '18 15:04

Maria Jeysingh Anbu


People also ask

How do I trigger the page refresh React?

Use reload() Method to Refresh a Page in React Manually Browsers natively provide a window interface with a location object, including the reload() method. It's a fairly simple method, as you can see in the example below.

What happens on page refresh React?

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.

Does React redirect refresh page?

react-router-dom allows us to navigate through different pages on our app with/without refreshing the entire component. By default, BrowserRouter in react-router-dom will not refresh the entire page.

How do I keep React component state after browser refresh?

To maintain state after a page refresh in React, we can save the state in session storage. const Comp = () => { const [count, setCount] = useState(1); useEffect(() => { setCount(JSON. parse(window. sessionStorage.


2 Answers

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.

like image 184
Abdellatif Derbel Avatar answered Sep 19 '22 00:09

Abdellatif Derbel


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 = "";   }; 
like image 32
pradeepradyumna Avatar answered Sep 19 '22 00:09

pradeepradyumna