react js : detect page refresh

16,205

The event beforeunload is executed just before window browser is being refreshed. Event is cancellable.

window.beforeunload = (e) => {
  console.log('Stop this');
  e.preventDefault()
  e.returnValue = '';
};

When using React an option is to take control in your Application component, or your most higher order component, in the componentDidMount lifecycle method as @georgim suggested instead componentWillUnmount as I first suggested, and manage there what you want to achieve.

Share:
16,205
learning_vba
Author by

learning_vba

Updated on August 02, 2022

Comments

  • learning_vba
    learning_vba almost 2 years

    I am new to react.js. I have a simple page with table. When I reload the page, state is getting lost. Is there a way to detect the browser refresh ?

    • Kokodoko
      Kokodoko over 6 years
      Single page apps shouldn’t reload the whole page, just if you don’t want to hard-resets your state.
    • learning_vba
      learning_vba over 6 years
      its not a single page app.
    • Hamza Baig
      Hamza Baig over 6 years
      @learning_vba You don't need renderTable(); in your MainHandler.js Because that'll be handled by Dashboard.js independently.
    • learning_vba
      learning_vba over 6 years
      thing is I dont want to change the existing logic. Is there anyway to detect browser refresh?
  • Giorgi Moniava
    Giorgi Moniava over 5 years
    what do you think about componentDidMount in the top level component? (to detect reload)
  • Dez
    Dez over 5 years
    @giorgim I have been trying it and besides it is better to use the beforeunload event listener, indeed it is more reliable to apply the logic in componentDidMount.
  • Anxifer
    Anxifer over 2 years
    this API is deprecated