I have two different lines of code, I’ve found one that works, but I don’t know why. I’d like some insight to React internals to understand the mechanics behind what is going on.
Here’s some context. I have a nested navigator, and I’m implementing a goBack functionality. The goBack functionality necessarily needs to go back in the nested navigator, not the root navigator. For example, if my navigation history is RootA -> NestedA -> NestedB…then going back should go to NestedA, not RootA.
In order to follow DRY principles, I made the goBack functionality a HOC wrapper. This is what it looks like:
export const withBack = (WrappedComponent) => {
const { colors } = useTheme();
const navigation = useNavigation();
return (props) => {
return <>
<SafeAreaView style={{ position: 'absolute', top: 0, left: 0, right: 0, zIndex: 1, }}>
<Appbar.Header style={{ backgroundColor: colors.onSurface, position: 'absolute', backgroundColor: 'transparent' }}>
<Appbar.BackAction onPress={() => navigation.goBack()} color='black'/>
</Appbar.Header>
</SafeAreaView>
<SafeAreaView style={{ flex: 1, backgroundColor: colors.onSurface}}>
<WrappedComponent {...props} />
</SafeAreaView>
</>;
}
}
I am using it in my nested stack navigator like this:
<Stack.Screen name="Branches"
component={withBack((props) => <Branches {...props} />)} />
However, doing so causes the back button to go back in root navigator, not the nested one.
Doing this instead gets the desired behavior:
<Stack.Screen name="Branches"
component={()=> withBack((props) => <Branches {...props} />)()} />
Can anyone explain to me why these two result in different behavior?