I'm working on a React application and I'm trying to listen to back button click events so I can customize the navigation flow. I've created the following hook:
export default function useBackButton(
goTo: string,
) {
const navigate = useNavigate();
useEffect(() => {
window.history.pushState(null, "", document.URL);
window.addEventListener("popstate", backButtonHandler);
return () => window.removeEventListener("popstate", backButtonHandler);
});
function backButtonHandler(event) {
navigate(goTo, { replace: true });
}
}
The problem with the code is that the callback method "backButtonHandler" in ...
window.addEventListener("popstate", backButtonHandler);
... will not be invoked.
It will only work if I add it as inline logic:
window.addEventListener("popstate", (event) => navigate(goTo, { replace: true });
I my case I need to provide the logic through a method declaration since I need to remove the listener.
Thanks in advance.