In this article, we will see how to detect when a user is leaving a page using React Router.
There are several use cases where we must detect if the user is leaving the page. For example, if user is filling some form on the website and click the back button by mistakenly, then we must and should warn the user that the data is not saved and it will be lost.
To detect when the user is leaving the page, we can use the useEffect
hook with a cleanup function. The cleanup function will be called when the component unmounts, which happens when the user leaves the page.
Here’s an example of how we can detect when the user is leaving the page using React Router:
import { useEffect } from 'react';
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
useEffect(() => {
const unlisten = history.listen(() => {
console.log('User is leaving the page');
// Do something before the user leaves the page
});
return () => {
console.log('Component is unmounting');
unlisten();
// Do something before the component unmounts
};
}, [history]);
return (
<div>
{/* Component content */}
</div>
);
}
Explanation
In the above example, we import the useHistory
hook from the React Router by which we can access to the browser’s history stack. We also use the useEffect
hook to set up a listener for changes to the history stack. The listener function will be called every time the user navigates to a new URL.
Inside the useEffect
hook, we create a cleanup function that will be called when the component unmounts. In the cleanup function, we remove the listener to prevent memory leaks.
With the above example, we can now detect when the user is leaving the page and trigger any necessary actions. For example, we could show a confirmation prompt before they leave the page.