'Why am I getting too many renders when trying to setState?

Here is my code. I'm grabbing data from firebase and placing it into my groupDataMap.

const Home = () => {
    
    const [memberInfo, setMemberInfo] = useState('');
    const auth = getAuth();
    const user = auth.currentUser;
    const memberId = auth.currentUser.uid
    const db = getDatabase();
    const dbRef = ref(db, 'groups');
    let groupDataMap = {};

    //get group name's if member_id(user) matches member id
    onValue(dbRef, (snapshot)=> {
        const data = snapshot.val();

        for(var key in data){
            if(data.hasOwnProperty(key)){
                const groupname = data[key]
                groupDataMap = groupname
            }
        }
    })
    setMemberInfo(groupDataMap)


I'm using memberInfo to populate a <li> element in my return:

 return (
        <div>
            <div class="brand">
                <h1>Headline</h1>
                <p>paragraph</p>
            </div>

            <ul class="list-group container-fluid">
                <li class="list-group-item">
                {memberInfo}
                </li>
            </ul>
        </div>
    );

Am I not just setting the state once?



Solution 1:[1]

Am I not just setting the state once?

No, setMemberInfo is going to be called again and again, so that the component renders infinitely.

Read about useEffect hook.

    const [memberInfo, setMemberInfo] = useState('');
    const auth = getAuth();
    const user = auth.currentUser;
    const memberId = auth.currentUser.uid

    useEffect(() => {
        const db = getDatabase();
        const dbRef = ref(db, 'groups');
        let groupDataMap = {};

        //get group name's if member_id(user) matches member id
        onValue(dbRef, (snapshot)=> {
            const data = snapshot.val();

            for(var key in data){
                if(data.hasOwnProperty(key)){
                    const groupname = data[key]
                    groupDataMap = groupname
                }
            }
        })
        setMemberInfo(groupDataMap)

    }, []); 

Tip: Refer this similar case to your question

Solution 2:[2]

You will have to use react's useEffect hook to set state.

Use this link for reference

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shri Hari L
Solution 2 Shubham Mistry