Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  178] [ 2]  / answers: 1 / hits: 5930  / 5 Years ago, tue, september 24, 2019, 12:00:00

I am trying to update the state of my component using props that I get from the parent component, but I get the following error message:




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




I want the local state to update if the prop changes.
The similar posts (Updating component's state using props, Updating state with props on React child component, Updating component's state using props) did not fixed it for me.



import React, {useState} from react


const HomeWorld = (props) => {
const [planetData, setPlanetData] = useState([]);
if(props.Selected === true){
setPlanetData(props.Planet)
console.log(planetData)
}


return(
<h1>hi i am your starship, type: {planetData}</h1>
)
}

export default HomeWorld

More From » reactjs

 Answers
1

You need to use the useEffect hook to run it only once.



import { useEffect }  from 'react'

...

const HomeWorld = (props) => {
const [planetData, setPlanetData] = useState([]);

useEffect(() => {
if(props.Selected === true){
setPlanetData(props.Planet)
console.log(planetData)
}
}, [props.Selected, props.Planet, setPlanetData]) // This will only run when one of those variables change

return(
<h1>hi i am your starship, type: {planetData}</h1>
)
}


Please notice that if props.Selected or props.Planet change, it will re run the effect.



Why Do I Get This Error ?




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




What is happening here is that when your component renders, it runs everything in the function, calling setPlanetData wich will rerender the component, calling everything inside the function again (setPlanetData again) and making a infinite loop.


[#6141] Saturday, September 21, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazlynnessencec

Total Points: 434
Total Questions: 113
Total Answers: 94

Location: Norway
Member since Mon, May 23, 2022
2 Years ago
;