What do you think will get logged – 50, 100 or 150?
None of it! It will log 10.
WHY?
React updates the state asynchronously. This means all synchronous code (like console.log) will execute immediately, and all setState will be scheduled for execution. Even if you put multiple console.log()
and add many more setAge methods, and the console will always print 10.
WHAT WILL BE THE FINAL VALUE OF age?
Let’s say we have {age} somewhere in the output. What do you think will be the final output?
It will be 110.
If you knew it, you quite know how to react works. If this puzzles you, check out this link.