Skip to content
Advertisement

How to fix Too many re-renders. React limits the number of renders to prevent an infinite loop

I am new to react and recently i got into this problem and i dont know how to solve it. it says Too many re-renders. React limits the number of renders to prevent an infinite loop. Hows it infinte loop? is it beacuase of on(“value”)?

import React from "react";
import fire from "./firebase";
import firebase from "firebase"
import { useState } from "react"

    
const UserPage = ({ match }) => {
    const [user, setUser] = useState(null)
    const { params: { userId } } = match;
    var userName;
    console.log(userId)
    firebase.database().ref("users/"+userId+"/praivate/login credentials").on("value", (snapshot)=>{
        setUser(snapshot.val().userName)
    })
    
    return(
        <>
        <h1>Hey {user}</h1>
        </>
    )
    }
   
export default UserPage
Plz help me to fix it, thank you.

Advertisement

Answer

You should do your Firebase staff inside a lifecyle method.As your working with functionnal components you can use the useEffect hook:

import React from "react";
import fire from "./firebase";
import firebase from "firebase"
import { useState } from "react"

    
const UserPage = ({ match }) => {
    const [user, setUser] = useState(null)
    const { params: { userId } } = match;

    useEffect(()=>{
        //Put your Firebase staff here
     },[])
    
    return(
        <>
        <h1>Hey {user}</h1>
        </>
    )
    }
   
export default UserPage

I dont know what you’re trying to achieve, but inside you <h1>{user}</h1> i think that {user} is an object so if you want to access a specific attribute you can do something like <h1>{user.attributeName}</h1>.

I hope that it helped

Advertisement