Fotios Tsakiris
Fotios Tsakiris

Reputation: 1558

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();;
  })

Upvotes: 5

Views: 6159

Answers (1)

Drew Reese
Drew Reese

Reputation: 202608

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 })
);

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.

Upvotes: 2

Related Questions