0

I need to print a message when a screen is opened or closed. I am using useEffect to show when the component mounts and when it unmounts. This is the code for useEffect:

  useEffect(() => {
     console.log("Starting Home");
    return () => {
        console.log("Ending Home");
    };
},[])

And the navigation in App.js:

    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={Home} />
        <Stack.Screen name="About" component={About} />
      </Stack.Navigator>
    </NavigationContainer>

Here, when I open the app, it automatically loads the Home screen. The app works properly with About page and prints messages when it is opened or closed. However, it prints the message for the home page only once when the app is opened.

Omar Diaa
  • 258
  • 4
  • 19

1 Answers1

2

If you want to show a message everytime a screen is focused you should use useFocusEffect instead of useEffect.

useEffect runs only when mounted and the Home screen is mounted only once.

Replace is with.

 useFocusEffect(
    React.useCallback(() => {
    console.log("Starting Home");
      return () => {
          console.log("Starting Home");
      };
    }, [])
  );

You will have to import it.

import { NavigationContainer ,useFocusEffect} from '@react-navigation/native';
Guruparan Giritharan
  • 15,660
  • 4
  • 27
  • 50
  • Thanks a lot man. It worked. But I have a question. Does the screen stay opened when I navigate to another page? Shouldn't be closed completely? – Omar Diaa Sep 13 '20 at 14:06
  • It stays on the stack actually, i have given a details explanation in this answer https://stackoverflow.com/a/61967910/1435722 – Guruparan Giritharan Sep 13 '20 at 14:24