1

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()?

3
  • What is the purpose of the index prop? Commented Oct 6, 2021 at 16:09
  • Could you try setting a unique keyprop to MyComponent in MainComponent ? I think it is because your MyComponent is getting unmounted & re-mounted on every render of MainComponent. To verify this, you can do console.log from an useEffect with empty dependency in MyComponent Commented Oct 6, 2021 at 16:42
  • I tried to add a unique key but still have same problem. I solved my problem by adding to each array id (create temporary now by Math.random() ) and change saveData method in parent component to that: const saveData = (data) => { let array = _.cloneDeep(dataArray); const index = _.findIndex(array, {id: data.id}); array.splice(index, 1, data); setDataArray(array); } I don't know if it correct/elegant way, but it works now Commented Oct 6, 2021 at 19:06

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.