'How to run a function when user clicks the back button, in React.js?
I looked around and tried to find a solution with React router.
With V5 you can use <Promt />
.
I tried also to find a vanilla JavaScript solution, but nothing worked for me.
I use React router v6 and histroy
is replaced with const navigate = useNavigation()
which doesn't have a .listen
attribute.
Further v6 doesn't have a <Promt />
component.
Nevertheless, at the end I used useEffect
clear function. But this works for all changes of component. Also when going forward.
According to the react.js docs, "React performs the cleanup when the component unmounts."
useEffect(() => {
// If user clicks the back button run function
return resetValues();;
})
Solution 1:[1]
Currently the Prompt
component (and usePrompt
and useBlocker
) isn't supported in react-router-dom@6
but the maintainers appear to have every intention reintroducing it in the future.
If you are simply wanting to run a function when a back navigation (POP action) occurs then a possible solution is to create a custom hook for it using the exported NavigationContext
.
Example:
import { UNSAFE_NavigationContext } from "react-router-dom";
const useBackListener = (callback) => {
const navigator = useContext(UNSAFE_NavigationContext).navigator;
useEffect(() => {
const listener = ({ location, action }) => {
console.log("listener", { location, action });
if (action === "POP") {
callback({ location, action });
}
};
const unlisten = navigator.listen(listener);
return unlisten;
}, [callback, navigator]);
};
Usage:
useBackListener(({ location }) =>
console.log("Navigated Back", { location })
);
If using the UNSAFE_NavigationContext
context is something you'd prefer to avoid then the alternative is to create a custom route that can use a custom history object (i.e. from createBrowserHistory
) and use the normal history.listen. See my answer here for details.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |