Handle the Browser Tab close event in React

avatar

Borislav Hadzhiev

Last updated: Apr 26, 2022

banner

Check out my new book

Handle the Browser Tab close event in React #

To handle the browser tab close even in React:

  1. Use the useEffect hook to add an event listener.
  2. Listen for the beforeunload event.
  3. The beforeunload event is triggered when the tab is about to be unloaded.
App.js
import {useEffect} from 'react'; const App = () => { useEffect(() => { const handleTabClose = event => { event.preventDefault(); console.log('beforeunload event triggered'); return (event.returnValue = 'Are you sure you want to exit?'); }; window.addEventListener('beforeunload', handleTabClose); return () => { window.removeEventListener('beforeunload', handleTabClose); }; }, []); return ( <div> <h2>hello world</h2> </div> ); }; export default App;

We added an event listener on the window object in our useEffect hook.

We passed an empty dependencies array to the useEffect hook, so it's only going to run when the component mounts.

The beforeunload event is triggered when the window or the tab is about to be unloaded.

The document is still visible and the event is still cancellable at this point.

This enables us to open a dialog asking the user if they really want to leave the page.

The user can either confirm and navigate to the new page or cancel the navigation.

Note that it's not certain that the event will trigger. For example, users are able to disable pop ups in their browser settings.

We used the addEventListener method to add an event listener on the window object.

The first parameter the method takes is the type of the event to listen for, and the second is a function that gets invoked when an event of the specified type occurs.

The function we returned from the useEffect hook is called when the component unmounts.

We used the removeEventListener method to remove the event listener that we previously registered.

The cleanup step is important, because we want to make sure we don't have any memory leaks in our application.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.