Do not use setState in componentDidMount
22 }
23
24 componentDidMount() {
25 this.setState({ optionsData: this.props.options} ); 26 }
27
28 handleClickOutside = () => {
Description
componentDidMount()
is invoked immediately after a component is mounted. This method is a good place to load data from an endpoint as it is invoked before the browser updates the screen.
Using setState()
in componentDidMount()
will trigger an extra rendering, so it causes performance issues as render()
will be called twice.
Bad Practice
var Hello = createReactClass({
componentDidMount: function() {
this.setState({
name: this.props.name.toUpperCase()
});
},
render: function() {
return <div>Hello {this.state.name}</div>;
}
});
Recommended
var Hello = createReactClass({
componentDidMount: function() {
this.onMount(function callback(newName) {
this.setState({
name: newName
});
});
},
render: function() {
return <div>Hello {this.state.name}</div>;
}
});
var Hello = createReactClass({
componentDidMount: function() {
this.props.onMount();
},
render: function() {
return <div>Hello {this.props.name}</div>;
}
});