Reputation: 386
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?
Upvotes: 4
Views: 1556
Reputation: 18113
Let's see the setState documentation
Think of setState() as a request rather than an immediate command to update the component
React does not guarantee that the state changes are applied immediately
Think of it as setTimeout(function test() {...}, 0);
a message will be added to the queue, the test
function will not be fired until all the stack is empty. You can find more information on the EventLoop documentation
Upvotes: 3
Reputation: 281696
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.
Upvotes: 10