How to detect browser back button event in react

To detect the browser back button event in React, you can make use of the “popstate” event and the “history” object. Here’s how you can achieve it:

  • Import the “useEffect” and “useCallback” hooks from the “react” package:

    import React, { useEffect, useCallback } from 'react';
  • Create a custom hook called “useBackButton” to handle the browser back button event:

    const useBackButton = (callback) => {
      const handleBackButton = useCallback(callback, [callback]);
    
      useEffect(() => {
        window.addEventListener('popstate', handleBackButton);
        
        return () => {
          window.removeEventListener('popstate', handleBackButton);
        };
      }, [handleBackButton]);
    };
  • Use the custom hook in your component by passing a callback function:

    const MyComponent = () => {
      const handleBackButton = () => {
        // Your logic for handling the back button event goes here
        console.log('Back button pressed!');
      };
    
      useBackButton(handleBackButton);
    
      return (
        // JSX of your component
      );
    };

In the above example, the custom hook “useBackButton” sets up the event listener for the “popstate” event and calls the provided callback function whenever the browser back button is pressed. Don’t forget to remove the event listener when the component is unmounted to prevent memory leaks.

You can replace the console.log statement in the “handleBackButton” function with your own custom logic to handle the back button event, such as showing a confirmation dialog or navigating to a different page.

Leave a comment