react-nativereact-hooksreact-native-navigation

React-Navigation useIsFocused always returns true, and I can't figure out why?


I have pretty simple use case for this, Basically if the screen is focused I want this function to run, if not don't run.


  const isFocused = useIsFocused();

  const onViewRef = useRef(({ viewableItems }) => {

    if (!isFocused) return;

    //code to run
  });

Here's the stack for this screen in particular:

const MyStack = () => {
  return (
    <Stack.Navigator headerMode="none">
      <Stack.Screen
        component={MyStackComponent}
        name="My"
      />
    </Stack.Navigator>
  );
};

And here is that stack being use in a tabNavigator

     <Tab.Screen
        component={MyStack}
        name="My"
      />
      <Tab.Screen
          component={Other Stack}
          name="Other"
        />
      

So basically whenever I go to any other tab on my app, the file using the useIsFocused hook should should return false right? Because right now it returns true no matter what, and I can't have that function running all the time. Any pointers?


Solution

  • to bring a real answer to this topic.

    For some reason, in my case too, useIsFocused() always return true; from the moment I arrive on the screen in question for the first time untill I kill the app (IOS).

    So I found another solution: use the navigation.isFocused() method from react-navigation. (https://reactnavigation.org/docs/navigation-prop/#isfocused)

    And it works perfectly ! Hoping it will help someone

    Here is my example:

    useEffect(() => {
            notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
                if (navigation.isFocused()) {
                    fetchConversationsList();
                }
            });
        }, [fetchConversationsList, navigation]);