Perviously when I wanted to make some actions when screen is opened I put them inside componentDidMount. For example I can fetch some data.
like this.>
The latest version of react-navigation provides custom hooks that let you react to focus and blur events: https://reactnavigation.org/docs/function-after-focusing-screen.
The following is an example from their docs that uses the onFocusEffect hook to make an API call on focus (it cleans up the effect when the screen goes out of focus):
import { useFocusEffect } from '@react-navigation/native';
function Profile({ userId }) {
const [user, setUser] = React.useState(null);
useFocusEffect(
React.useCallback(() => {
const unsubscribe = API.subscribe(userId, user => setUser(data));
return () => unsubscribe();
}, [userId])
);
return ;
}