Uncaught Invariant Violation: Maximum update depth exceeded

Viewed 796

I'm trying to set state after a function has finished and I'm getting the error:

Uncaught Invariant Violation: Maximum update 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. 

I'm calling setstate in a callback after the function has finished so I thought this would work ok from what I've read, but I can't seem to make it work.

Running the function addStuff when component updates

componentDidUpdate() {
   this.addStuff(() => this.setState({"loading":false}))
}

Setting a callback when complete

addStuff(callback) {
    ...Does a bunch of stuff
    callback();
}

Can anyone suggest what I may be doing wrong here? Thanks.

2 Answers

The reason for the infinite loop is that you did not wrap your setState in a condition, but in a callback.

So what I think happens is that as soon as your component updates, setState is called, which triggers a re-render, which means that componentDidUpdate is called, which sets state, which triggers a re-render, which calls componentDidUpdate , etc.

This is the reason why setting state in componentDidUpdate should always be conditional, as specified in the example in the docs. In your case, maybe it could look like this, where you compare relevant props to verify that you indeed need to rerender :

componentDidUpdate(prevProps) {
  if (this.props.relevantProp!== prevProps.relevantProp) {
    this.addStuff(() => this.setState({"loading":false}))
  }
}

if you read the React Docs, it clears states "You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example above, or you’ll cause an infinite loop." So with your function it is the same thing that is happening.

Related