Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackHandler.removeEventListener is not wotking in react-native for android

Tags:

react-native

Cannot get BackHandler.removeEventListener to work. Can anyone please guide as of how to use it?

like image 209
Yasser Zubair Avatar asked Dec 28 '25 16:12

Yasser Zubair


2 Answers

componentDidMount() {
  this.backHandler = BackHandler.addEventListener('hardwareBackPress', handler);
}

componentWillUnmount() {
  this.backHandler.remove();
}
like image 179
Nick Jang Avatar answered Jan 02 '26 01:01

Nick Jang


An update on how to do it with hooks - I finally made it working by keeping the function we are passing in BackHandler.addEventListener inside useEffect only and with it by using isFocused method of navigation. Any change in the following code breaks it -

useEffect(() => {
    const backAction = () => {
        if (navigation.isFocused()) {
            Alert.alert("Hold on!", "Are you sure you want to exit the app?", [
                {
                    text: "Cancel",
                    onPress: () => null,
                    style: "cancel"
                },
                { text: "YES", onPress: () => BackHandler.exitApp() }
            ]);
            return true;
        }

    };
    const backHandler = BackHandler.addEventListener("hardwareBackPress", backAction);
    return () => backHandler.remove();
}, [])

This is my second answer, if it helps please mark this as useful.

like image 35
Rohit Advani Avatar answered Jan 02 '26 02:01

Rohit Advani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!