Avoid usage of `setState` in `componentDidUpdate`JS-0443
Updating the setState
inside componentDidUpdate
can create an infinite loop because there's no break condition.
Why does componentDidUpdate()
create an infinite loop?
When developers call an AJAX call in componentDidUpdate
, the developer sets the state on the callback, triggering another call and update.
However, if there is some event in parent Component, setState()
is triggered and as a result, componentDidUpdate()
of child Component gets executed as componentDidUpdate()
was causing an infinite loop (as it triggers setState()
inside child component).
How to prevent infinite loop?
The developers can call setState()
immediately in componentDidUpdate()
but note componentDidUpdate()
is called after componentDidMount()
. Like mentioned before, to avoid an infinite loop, the API call needs to be inside a conditional statement.
Bad Practice
var Hello = createReactClass({
componentDidUpdate: function() {
this.setState({
name: this.props.name.toUpperCase()
});
},
render: function() {
return <div>Hello {this.state.name}</div>;
}
});
Recommended
var Hello = createReactClass({
componentDidUpdate: function() {
this.props.onUpdate();
},
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
// Example 2
var Hello = createReactClass({
componentDidUpdate: function() {
this.onUpdate(function callback(newName) {
this.setState({
name: newName
});
});
},
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
## References
- [ComponentDidUpdate infinite loop](https://www.xspdf.com/resolution/57652266.html)