Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
How to Implement beforeunload event Listener in React

I have this rough code in Javascript, I want to implement this code in my react application but I am not sure how to implement them in react.

Overview of my requirement --

I want to clear a particular token from local storage unless the user closes all the tabs or exits the browser, so the next time user tries to open the application he needs to log in again, So I took a reference of this code, but I don't have any idea where to use this in React.

window.onbeforeunload = (event) => {
    localStorage.removeItem('logged-in');
}

let loggedIn = localStorage.getItem('logged-in');
let sessionLoggedIn = sessionStorage.getItem('logged-in');
if(!loggedIn) {
    if(sessionLoggedIn) {
        localStorage.setItem('logged-in', JSON.parse(sessionLoggedIn));
        //go to authenticated space
        window.location.href = '/authenticated';
    } else {
        //go to login
        window.location.href = '/login';
    }
} else {
    //go to authenticated space
    window.location.href = '/authenticated';
}

window.addEventListener('storage', (event) => {
    if (event.key == 'logout' && event.newValue) { 
        sessionStorage.removeItem('logged-in');
        localStorage.removeItem('logout');
        window.location.href = '/login';
    }
});

Can someone guide me on where to implement this code in react application do we need to use any hooks for watching for beforeunload event?

Any help would be much appreciable, thanks in advance!!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

With the limited information given I would say that you should put the following code into your index.js or similar.

    useEffect(() => {
      window.addEventListener('beforeunload', yourFunction)
     
      return () => {
      window.removeEventListener('beforeunload', yourFunction)
    };
  }, []);
about 4 years ago · Juan Pablo Isaza Report

0

use it like this

useEffect(() => {
  window.addEventListener("beforeunload", handleUnloadEvent);

  return () => window.removeEventListener("beforeunload", handleUnloadEvent);
}, [handleUnloadEvent]);

I've added [handleUnloadEvent] to the 2nd attribute of useEffect to prevent adding and removing the event listener on every state change.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!