Lesson

Avoid pitfalls with reading React component state right after running setState

One of common pitfalls that many React developers experience is trying to read an 'updated' state of the component right after it was updated using setState, for example:

Duration
2 min
Access
Free
Transcript
Available

One of common pitfalls that many React developers experience is trying to read an 'updated' state of the component right after it was updated using setState, for example:

this.setState({counter: 5});
console.log(this.state.counter);

In this lesson we are going to learn why reading this.state right after executing setState may lead to inconsistent results and how to use setState callback function to read the updated state value as soon as it was updated.