DeviousMutant
DeviousMutant

Reputation: 1

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

The code was originally supposed to just display a different greeting using the time of the day (Date().getHours()) and some conditions. However, I tried to simplify the code to just check if the state would change, it gives the same error mentioned above.

The state does get displayed as is if I don't include the conditions setting the state.

import React from 'react'
import Cards from './cards'

function Main() {

    const [greeting, setGreeting] = React.useState("Hello")
    const user = false
    if (user) {
        setGreeting("Welcome")
    } else {
        setGreeting("You dont belong here")
    }
    return (
        <main role="main" className="col-md-9 ml-sm-auto col-lg-10 px-md-4">
            <div className="d-flex flex-wrap flex-md-nowrap pt-2 mt-2 mb-4">
                <h1> {greeting} Random Dude!</h1>
            </div>
            <Cards />
        </main>
    )
}


export default Main

I tried to wrap this in a function as well but no luck which makes sense because every time the code gets rendered, the function is called again and it loops

import React from 'react'
import Cards from './cards'

function Main() {

    const [greeting, setGreeting] = React.useState("Hello")
    const user = false
    function greetingMessage() {
        if (user) {
            setGreeting("Welcome")
        } else {
            setGreeting("You dont belong here")
        }
        return (greeting)
    }
    return (
        <main role="main" className="col-md-9 ml-sm-auto col-lg-10 px-md-4">
            <div className="d-flex flex-wrap flex-md-nowrap pt-2 mt-2 mb-4">
                <h1> {greetingMessage()} Random Dude!</h1>
            </div>
            <Cards />
        </main>
    )
}


export default Main

Upvotes: 0

Views: 133

Answers (2)

Lakshya Thakur
Lakshya Thakur

Reputation: 8316

You need to perform setting your React state inside either an event handler or inside a useEffect hook.

What's happening in your code is this:-

1) const user = false :- This assignment happens every time the component re-renders so I think user should be React state and not a simple variable.

2) <h1> {greetingMessage()} Random Dude!</h1> - This means that whenever your component renders, greetingMessage() is called and the state is set as per your logic. Now since, the state is set, the component will re-render, which will trigger everything again and the cycle will go on. To solve this do this in a useEffect like so:-

//Just after your state definitions
useEffect(()=>{
        if (user) {
            setGreeting("Welcome")
        } else {
            setGreeting("You dont belong here")
        }
},[])

So your final code can be something like:-

function Main() {

    const [greeting, setGreeting] = React.useState("Hello")
    //Implement the logic for how you want to set this user state
    const [user,setUser] = React.useState(false)


    useEffect(() => {
    if (user) {
            setGreeting("Welcome")
        } else {
            setGreeting("You dont belong here")
        }
    }, [])

    return (
        <main role="main" className="col-md-9 ml-sm-auto col-lg-10 px-md-4">
            <div className="d-flex flex-wrap flex-md-nowrap pt-2 mt-2 mb-4">
                <h1> {greeting} Random Dude!</h1>
            </div>
            <Cards />
        </main>
    )
}

My best bet for you is to once go through React docs about hooks before you jump directly into code. These will clear out a lot of things for you:-

https://reactjs.org/docs/hooks-intro.html

Upvotes: 2

Karthick Vinod
Karthick Vinod

Reputation: 1437

See if this works

import React from 'react'
import Cards from './cards'

function Main() {
    const user = false
    const [greeting, setGreeting] = React.useState(user ? "Welcome" : "You dont belong here")

    return (
        <main role="main" className="col-md-9 ml-sm-auto col-lg-10 px-md-4">
            <div className="d-flex flex-wrap flex-md-nowrap pt-2 mt-2 mb-4">
                <h1> {greeting} Random Dude!</h1>
            </div>
            <Cards />
        </main>
    )
}


export default Main

Upvotes: 0

Related Questions