How to detect/handle back button press in React?

Viewed 749

I am trying to detect a user pressing the back button. I have a component that logs POP every time, even when the user did not press back button. I want to run this code only when the user navigated to the component from another screen. How do I do this?

const history = useHistory();
useEffect(() => {
    console.log(history.action)
    if (history.action == 'POP') {
        // process
}, [data])
1 Answers

I am not quite sure what you're trying to accomplish here but I think you could use the return in useEffect to check when the user goes back. return runs when the component is unmounted.

const history = useHistory();
useEffect(() => {
    console.log(history.action)
    if (history.action == 'POP') {
        
        return function cleanup() {console.log("User pressed back")};
}, [data])
Related