Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will code after setState() in React be run?

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?

like image 737
alehel Avatar asked Sep 02 '25 16:09

alehel


1 Answers

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.

like image 50
Shubham Khatri Avatar answered Sep 04 '25 07:09

Shubham Khatri