BitTree
BitTree

Reputation: 55

Maximum update depth exceeded. React

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

Answers (1)

smac89
smac89

Reputation: 43234

Notice what happens when a child component updates its data:

  1. It calls parent.saveData
  2. This triggers a state change in the parent because the data array has changed
  3. Because you didn't pass a key prop to children, React has no choice but to re-render all children with the updated data
  4. Each child notices that its data prop has changed. This triggers the useEffect, so it also calls parent.saveData
  5. The process repeats while the original render is still taking replace, etc, etc

Solution

  1. Pass a key prop to each child. Do not use the index as key, instead use something that reflects the data being passed to the components

Upvotes: 2

Related Questions