I remember how surprised I was when I found out that setState
was async. Now I stumbled upon a "strange" behaviour that doesn't fit into my understanding of setState
asynchronicity.
Consider a snippet below (for some reason it results in Script Error
, here's the external sandbox: https://codesandbox.io/s/zwrvkz74y3):
class SomeComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
prop1: 1,
prop2: 2
};
setTimeout(this.changeProp1.bind(this), 100);
}
componentDidUpdate() {
console.info("componentDidUpdate called");
}
changeProp1() {
this.setState({ prop1: 2 });
this.changeProp2();
}
changeProp2() {
this.setState({ prop2: 3 });
}
render() {
const { prop1, prop2 } = this.state;
return React.createElement('div', null, `prop1: ${prop1}, prop2: ${prop2}`);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(React.createElement(SomeComponent), rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
If you run this and check the console you will see that componentDidUpdate
was invoked twice, but shouldn't the setStates
accumulate and update the Component just once?
UPDATE: I think my confusion comes from this phrase in the State Updates May Be Asynchronous section on ReactJS website:
React may batch multiple setState() calls into a single update for performance.