Reputation: 55
I have a little problem with my code. When I render my component I've got this error on console console
Maximumupdate depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
Below is part of my sample code:
MainComponent:
const saveData = (data) => {
setDataArray(prevState => [...prevState, data]);
}
return (
<Fragment>
{dataArray.map((element, index) => {
return (<MyComponent data={element} index={index} save={saveData}/>)
})}
</Fragment>
)
dataArray is an array of objects
MyComponent:
const MyComponent = (props) => {
const [data, setData] = useState(props.data);
useEffect(() => {
props.save(data);
}, [data]);
}
Is the problem in updating the state up to main component? Or I can't render my child component using map()?
Upvotes: 1
Views: 11506
Reputation: 43234
Notice what happens when a child component updates its data
:
parent.saveData
key
prop to children, React has no choice but to re-render all children with the updated data
useEffect
, so it also calls parent.saveData
Upvotes: 2