Avoid using `setState` in `componentWillUpdate`JS-0459
Avoid using setState()
inside componentWillUpdate()
because it is called every time a render is required, such as when this.setState()
is called.
Having this.setState
call inside componentWillUpdate
might sometimes lead to indefinite calls/loops.
We can call setState
inside componentWillUpdate
under certain conditions but it is recommended not to do so.
Use setState
only in in these lifecycle methods, i.e., componentDidMount
, componentWillReceiveProps
, shouldComponentUpdate
.
componentWillUpdate
receives two arguments, i.e., props
and state
. This lifecycle method is mainly used to handle changes in the props/state
and prepare for the subsequent rendering.
Use cases like animations, dispatching an event based on conditions, change values based on certain conditions, etc.
Bad Practice
const Hello = createReactClass({
componentWillUpdate() {
this.setState({
name: this.props.name.toUpperCase()
});
},
render() {
return <div>Hello {this.state.name}</div>;
}
});
Recommended
const Hello = createReactClass({
componentWillUpdate() {
this.props.prepareHandler();
},
render() {
return <div>Hello {this.props.name}</div>;
}
});