I have a more complex setup, but have boiled my hook down to the most minimum example:
import { useEffect } from "react";
const useUnsavedChangesAlert = () => {
useEffect(() => {
const handleRouteChange = (event) => {
console.log("IN HANDLE ROUTE CHANGE!!");
};
console.log("ADD POPSTATE EVENT LISTENER!!");
window.addEventListener("popstate", handleRouteChange);
return () => {
console.log("REMOVE POPSTATE EVENT LISTENER!!");
window.removeEventListener("popstate", handleRouteChange);
};
}, []);
};
export default useUnsavedChangesAlert;
The purpose of this is the class ‘Are you sure?’ popup when a user attempts to navigate away from a page, where they might lost some changes. While I have removed that functionality just for proof of concept, I would tend to expect that when I click the back button, the popstate event listener would fire the handleRouteChange function and then the page would route away and the useEffect return would unregister the event listener.
However, the log statement in the handleRouteChange function is not printing at all. Is it possible that the cleanup function is running, therefore unregistering the event listener, before the event listener has a chance to fire? I was under the impression that the event listener fired first.
Is this what is happening, or is there a different problem here? What might be a good way to fix this so that I can have the event listener fire prior to the cleanup function running?