Update [Custom Android back button behavior] example
Hi! I am currently refactoring code to using hooks. And I found refactoring the custom back button behaviour confusing.
I tried to adapt the example you have here to the code I refactored
import React from "react";
import { BackHandler } from "react-native";
const ScreenWithCustomBackBehavior = ({ navigation }) => {
const onBackButtonPressAndroid = useCallback(() => {
if (isSelectionModeEnabled()) {
disableSelectionMode();
return true;
} else {
return false;
}
}, [isSelectionModeEnabled, disableSelectionMode]);
useEffect(() => {
const _didFocusSubscription = navigation.addListener('didFocus', () => {
BackHandler.addEventListener('hardwareBackPress', onBackButtonPressAndroid);
});
const _willBlurSubscription = navigation.addListener('willBlur', () => {
BackHandler.removeEventListener('hardwareBackPress', onBackButtonPressAndroid);
});
return () => {
if (_didFocusSubscription) {
_didFocusSubscription.remove();
}
if (_willBlurSubscription) {
_willBlurSubscription.remove();
}
};
}, [navigation, onBackButtonPressAndroid]);
}
return (
// ...
)
Do you think it's a proper way to do it? If yes, should I submit a PR?
Thank you
@KarinaDavtyan hello! I'll be honest: in the company I work for we upgraded to a version of RN with hooks only ~ 2 weeks ago and so far I didn't have a chance to write any hook-enabled react code, and so I'm not very knowledgeable of the syntax yet.
That being said, upon first sight, I find the code a little hard to read - imho the existing code at https://reactnavigation.org/docs/en/next/custom-android-back-button-handling.html is very easy to read, while I daresay that the above snippet will, to me at least, remain somewhat hard to read even after I use hooks regularly.
My general advice would be not to refactor code just for the sake of using hooks. Personally, I'd just use the package mentioned in the docs (but I'm its author so I'm biased 😆 ).
Thank you for the quick reply! @vonovak
My general advice would be not to refactor code just for the sake of using hooks.
I wouldnt say it was the motivation 😅 We started with refactoring context to useContext which looks better now, in my opinion. And then we were just trying it out in other parts as well.
the above snippet will, to me at least, remain somewhat hard to read even after I use hooks regularly.
Agree, it is far from perfect. I was just hoping to have some feedback 🙂
I guess for now better, we just leave code as it is, following the example https://reactnavigation.org/docs/en/next/custom-android-back-button-handling.html
We can probably provide some hook based API to do this: https://github.com/react-navigation/hooks
That would be great! I would be happy to help with testing or anything
cc @slorber
Hi,
Makes sense to have a hook for that, I'll see how I can add this to react-navigation-hooks soon
thankyou, your code very helpful