I have a simple application with the navigation built with react-router
v6. My use case is to call an API with the last updated state on page unload.
const handleBeforeUnload = () => {
console.log("Running unload");
};
React.useEffect(() => {
window.addEventListener("beforeunload", handleBeforeUnload);
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, []);
With the above code when I reload the browser the handler is getting called. But when I'm trying to navigate via sidebar having NavLink
, the unload is not getting called because react-router-dom
do client side routing so page is not actually never getting unload. So How can I run the piece of code on page unload with react-router-dom
Navigation?
Sample Code:- https://codesandbox.io/s/lingering-pond-gt5u6d
You'll need to handle all the different ways a user leaves the component differently. Use beforeunload
when the page is reloaded or closed, use an effect cleanup function to handle when the component is just unmounted.
Example:
React.useEffect(() => {
const handleBeforeUnload = () => {
console.log("Running unload");
};
// handles when page is unloaded
window.addEventListener("beforeunload", handleBeforeUnload);
// cleanup function handles when component unmounts
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
handleBeforeUnload();
};
}, []);