Call a function when focused screen changes
In this guide we will call a function or render something on screen focusing. This is useful for making additional API calls when a user revisits a particular screen in a Tab Navigator, or to track user events as they tap around our app.
There are multiple approaches available to us:
- Listening to the
'focus'event with an event listener. - Using the
useFocusEffecthook provided by react-navigation. - Using the
useIsFocusedhook provided by react-navigation.
Triggering an action with a 'focus' event listener
We can also listen to the 'focus' event with an event listener. After setting up an event listener, we must also stop listening to the event when the screen is unmounted.
With this approach, we will only be able to call an action when the screen focuses. This is useful for performing an action such as logging the screen view for analytics.
Example:
- Static
- Dynamic
import * as React from 'react';
import { View } from 'react-native';
function ProfileScreen() {
const navigation = useNavigation();
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
alert('Screen is focused');
// The screen is focused
// Call any action
});
// Return the function to unsubscribe from the event so it gets removed on unmount
return unsubscribe;
}, [navigation]);
return <View />;
}
import * as React from 'react';
import { View } from 'react-native';
function ProfileScreen() {
const navigation = useNavigation();
React.useEffect((