Why is setState giving me the wrong value?

Posted by Prem Tiwari | Updated on

In React, both this.props and this.state represent the rendered values, i.e. what’s currently on the screen.

Calls to setState are asynchronous – don’t rely on this.state to reflect the new value immediately after calling setState. Pass an updater function instead of an object if you need to compute values based on the current state (see below for details).

Example of code that will not behave as expected:

If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.

Related Questions & Answers