alexunder alexunder - 22 days ago 14
Javascript Question

What happens when using this.setState multiple times in React component?

I wanted to check what happens when you use this.setState multiple times (2 times for the sake of the discussion).
I thought that the component will be rendered twice but apparently it's rendered only once. Another expectation I had was that maybe the second call for setState will run over the first one, but you guessed it - worked fine.

Link to a JSfiddle

var Hello = React.createClass({
render: function() {
return (
<div>
<div>Hello {this.props.name}</div>
<CheckBox />
</div>
);
}
});

var CheckBox = React.createClass({
getInitialState: function() {
return {
alex: 0
};

},
handleChange: function(event) {
this.setState({value: event.target.value});
this.setState({alex: 5});
},
render: function() {
alert('render');
return (
<div>
<label htmlFor="alex"> Alex </label>
<input type="checkbox" onChange={this.handleChange} name="alex" />
<div>{this.state.alex}</div>
</div>
);
}
});

ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);


As you'll see, an alert that says 'render' pops up on every render.

Do you have an explanation for why it worked properly?

Answer

React batches state updates that occur in event handlers and lifecycle methods. Thus, if you update state multiple times in a <div onClick /> handler, React will wait for event handling to finish before re-rendering.

To be clear, this only works in React-controlled synthetic event handlers and lifecycle methods. State updates are not batched in AJAX and setTimeout event handlers, for example.