Search code examples
firebasereact-nativeinfinite-loopreact-state-managementuse-effect

Infinite Loop - React Native useState useEffect


I am new to hooks and was under the impression that useEffect only ran once on the page load. I am setting the interests state variable to a returned firebase response but it is hitting an infinite loop. Why would this be happening? It is also to my understanding that the firebase .once method should only pull back the data once.

const ProfileCardScreen = ({navigation}) => {
    const user = navigation.getParam('user');
    const [interests, setInterests] = useState([]);

    const getUserProfileData = () => {
        var userId = user.uid;
        firebase.database().ref('/Users/' + userId).once('value').then(function(snapshot) {
            var interests = (snapshot.val() && snapshot.val().interests);
            Object.keys(interests).map(function(key) {
                setInterests(interests);
              });
        });
    };

    useEffect(() => {
        getUserProfileData();
    });

Solution

  • Yes, you can use useEffect() to run something as soon as the page loads. To achieve this though, you'll have to add a second argument, in this case, an empty array, to only run on mount and unmount (otherwhise it also runs on update).

    Meaning, it should look like this:

    useEffect(() => {
        getUserProfileData();
    }, []);
    

    Side note: By adding a state variable inside the empty array (like this: [myState]) you'll create a listener for that state. In this case, the useEffect would work as a "didUpdate" function for this state only.