Trying to understand the workings of setState() in React. My question is this.
If I have a function where one of the lines is setState(), will code lines AFTER this line still be run before the rerendering? For instance, in the code bellow,
foo(value) {
this.setState({stateValue: value});
console.log("Stuff after setState");
}
In that code, is the console.log guaranteed to run? It runs when I test it, but I'm uncertain if this is just because React hasn't had time to re-render yet. Can I expect code after this.setState() to run?
setState
is asynchronous
function and just like any asynchronous function is being passed on to the event loop, setState
also is passed on to the event loop and any code after it will execute seemlessly.
Once the setState method has completed executing, it will trigger the render method, which is when React will work on the document render.
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