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?
React may batch multiple setState calls into a single update for performance. Because props and state may be updated asynchronously, you should not rely on their values for calculating the next state.
If you have ever tried to set a state variable multiple times in a row in a React component, you may have been surprised to find that it didn't quite work. It would be reasonable to expect that, every time you click the “Increment Twice” button, count will increase by two.
This is an intended behavior of a setState(callback) method wrapped in a <React. Strict> component. The callback is executed twice to make sure it doesn't mutate state directly.
Inside it, the Clock component schedules a UI update by calling setState() with an object containing the current time. Thanks to the setState() call, React knows the state has changed, and calls the render() method again to learn what should be on the screen.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With