Home > Software design >  How to run a function when user clicks the back button, in React.js?
How to run a function when user clicks the back button, in React.js?

Time:03-08

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 Edit how-to-run-a-function-when-user-clicks-the-back-button-in-react-js

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.

  • Related