Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

234
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda