DEV Community

Discussion on: How To Create A Simple Alert For An onbeforeunload Event (Closing Browser or Navigating Away From Page) [updated]

Collapse
 
lexlohr profile image
Alex Lohr

Do not directly use window.onbeforeunload, as it will overwrite all other event listeners. Instead, use the following effect:

useEffect(() => {
  if (shouldIntervene) {
    const listener = () => true
    window.addEventListener('beforeunload', listener)
    return () => window.removeEventListener('beforeunload', listener)
  }
}, [shouldIntervene])
Enter fullscreen mode Exit fullscreen mode

This has the added advantage of automatically unsubscribing from the event.

Collapse
 
tiaeastwood profile image
Tia Eastwood

Fantastic, thanks for the tip!