
Last updated: Apr 7, 2024
Reading time·2 min

To handle the browser tab close even in React:
useEffect hook to add an event listener.beforeunload event.beforeunload event is triggered when the tab is about to be unloaded.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>bobbyhadz.com</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.
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); }; }, []);
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.
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 to the window object.
window.addEventListener('beforeunload', handleTabClose);
The function we returned from the useEffect hook is called when the component
unmounts.
return () => { window.removeEventListener('beforeunload', handleTabClose); };
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.