Skip to main content

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:

  1. Listening to the 'focus' event with an event listener.
  2. Using the useFocusEffect hook provided by react-navigation.
  3. Using the useIsFocused hook 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:

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 />;
}