30
loading...
This website collects cookies to deliver better user experience
Home
and the second, Details
.Home
to the Details
page,Home
component to unmount, and the Details
component to mount. If I navigate back, I'd expect the Home
component to mount again at that point.Home
to Details
, Home
does not unmount as it remains part of the stack, even as the Details
component mounts. When you navigate back in the stack to Home
, as the component was never unmounted, it just come back into focus. Note however, that at this point, the Details
component does unmount, since it is no longer part of the stack. Check out the documentation if you'd like more information.useEffect
hook and rely on this to be called upon the component mounting, but this clearly doesn't work with mobile stack navigation due to the difference in lifecycle for React Native.useEffect
hook. The sequence of events is therefore:focus
listener. As the screen is currently in focus, it makes an immediate API call.useEffect
hook, and thus the focus
listener is still in play.function Profile({ navigation }) {
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// Make API call here
})
return unsubscribe
}, [navigation])
return <ProfileContent />
}
return unsubscribe
in the example above.useFocusEffect
hook that's provided by React Navigation. This is similar to React's useEffect
hook but runs on a screen being in focus instead.import { useFocusEffect } from '@react-navigation/native'
function Profile() {
useFocusEffect(
React.useCallback(() => {
let isActive = true
const fetchList = async () => {
try {
const tests = (await listApiService.list()).data
if (isActive) {
setList(test)
}
} catch (_) {
setError('Something went wrong')
}
}
fetchList()
return () => {
isActive = false
}
}, []),
)
return <ProfileContent />
}
useCallback
function to ensure that your API doesn't get called unnecessarily.