Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

244
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda