How to cleanup useEffect in React Native while using React Navigation?

Viewed 1328

I am using random user api to fetch user information with setInterval function and my useEffect looks like this;

// Users.js

useEffect(() => {
    const getUser = () => {
      fetch("https://randomuser.me/api")
        .then((res) => res.json())
        .then((data) =>
          setUsers((prevUsers) => {
            return setUsers([
              ...prevUsers,
              { key: data.results[0].login.uuid, value: data.results[0] },
            ]);
          })
        );

      console.log("cleanup?");
    };
    getUser();
    // const userInterval = setInterval(getUser, 5000);
    // return () => clearInterval(userInterval);
  }, []);

I use react navigation to display each user's details in another page and navigate like this;

 <TouchableOpacity
 onPress={() => navigation.navigate("userDetails", item.value)}>

So when I nagivate to details page, useEffect doesn't return which means component doesn't unmount. It actually makes because of the stack navigation, pages are basically on top of each and still running. So how can I stop my interval function in this case?

1 Answers

These scenarios are covered in the docs of react-navigation.

From the docs:

React Navigation emits events to screen components that subscribe to them. We can listen to focus and blur events to know when a screen comes into focus or goes out of focus respectively.

Example:

function Profile({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      // Screen was focused
      // Do something
    });

    return unsubscribe;
  }, [navigation]);

  return <ProfileContent />;
}   

Or with the help of useFocusEffect hook above code can be simplified to this.

import { useFocusEffect } from '@react-navigation/native';

function Profile() {
  useFocusEffect(
    React.useCallback(() => {
      // Do something when the screen is focused

      return () => {
        // Do something when the screen is unfocused
        // Useful for cleanup functions
      };
    }, [])
  );

  return <ProfileContent />;
}
Related