useBackButton Hook

At least Android phones have a (software) “Back” button that needs to be supported in apps. The desired behavior of the Back button is to go back to the previous level in the application (at least, in a layered application). At the top level, the Back button exits the application. When a modal window is open (including the menu), the Back button will close that modal window.

The handling of the back button is through a hook, which in turn adds an event listener.

The hook uses the BackHandler from React Native. When using the hook, it seems that the context of the hook is when the component first rendered. Therefore, the event listener does not use the current data in the component. I’m not sure I understand this completely. However, the (callback) function passed to the hook has to be fully self-sufficient, that is, not use any of the data in the component.

Example usage:

import useBackButton from '../utils.useBackButton';

function MyComponent(props) {
  useBackButton(() => {
    // Back button has to get the data independently
    const bbData = MyStore.getData();
    alert(`Back button is pressed, data: ${bbData}.`);
  });

  // data the component operates
  const data = MyStore.getData();
  ... rest of the component
}