Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 navigate to the 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?

like image 319
İlker Avatar asked Jun 04 '26 23:06

İlker


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 />;
}
like image 133
Murli Prajapati Avatar answered Jun 07 '26 12:06

Murli Prajapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!