Problem

While using React-navigation, I realised that when I navigate away from a component using the navigation.push method, the component is not getting unmounted and as a result the return function in the useEffect hook is not getting called.

For example this is my code when I am using Apollo React Native client to poll for data and when the component is unmounted, the useEffect stops the polling by doing the cleanup/unsubscription:

useEffect(() => {
        startPolling(2000);

      return () => {
        stopPolling();
      }
    },[]);

Solution

In order to make the component unmount, use navigation.replace("componentName") to navigate away from the component instead of navigation.push("componentName"). This way, you get the same functionality of navigation.push() yet you are also able to make the React Native component to unmount.