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.
2
Answers
If you need to listen to
back button
events you can create afunction
like this:Then, include the same in your
component
as follows:Reference link: Intercept/handle browser’s back button in React-router
You’re forgetting a dependency array in your
useEffect
. This leads the event listener to be added and removed on each render. Just add an empty array as a dependency.