Prakash Subba
Prakash Subba

Reputation: 79

setState inside useEffect cause infinite loop

I want to use the list to seData and setUserData. I am using data to map through the list of users and display on the table. I am using the userData to get user information in different components. This is causing infinite loop.

import { useState, useEffect, useContext } from 'react';
import { collection, onSnapshot } from 'firebase/firestore';
import { db, auth } from '../../firebase';
import { UserContext } from '../../Contexts/UserContext';

const Datatable = () => {
    const {userData, setUserData} = useContext(UserContext);
    const [data, setData] = useState([]);
    const [isEditing, setIsEditing] = useState(false);
    const [currentId, setCurrentId] = useState("");

    useEffect(() => {
        const getUserData = () => {
            onSnapshot(collection(db, "users"), (snapshot) => {
                let list = [];
                snapshot.docs.forEach((doc) => {
                list.push({ id: doc.id, ...doc.data() });
                setData(list);
                setUserData(list)
                });
            }, (err) => {
            console.log(err);
            });
        }
        getUserData();
    }, [])
}

Upvotes: 1

Views: 1278

Answers (1)

Sujith Sandeep
Sujith Sandeep

Reputation: 1249

Updating values to the state should not be done in useEffect. You have to create a function outside and update the state value.

If you do so, You will be getting Warning: Maximum update depth exceeded. error.

This happens because once if you update a state the reference of the state will be changed and component rerender happens. Again since the reference is changed. The useEffect will be called again and this happens infinitely which the react stops after a certain extent.

Upvotes: 1

Related Questions