Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Avoid pitfalls with reading React component state right after running setState

    Tomasz ŁakomyTomasz Łakomy
    reactReact

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: We have a simple React application, which allows me to increment the counter when I'm clicking the button. Over here, we have the implementation of this component. Essentially, we have a button, and on click, I am incrementing the counter by one, displaying this counter in this span.

    By default, we set the counter to zero. We would like to see how the counter value exactly changes. I have two console logs. One of them is inside of the render function, and another one inside of the hundredClick function, right after we update the state.

    Let's take a look inside of the console. Let me refresh this page. Right now, we have by default, counter render equals zero, because this is the default state we set over here. If I click this button once, we're going to see something interesting.

    The counter in render is set to one, but the counter right after I've updated this state is actually still equal to zero. The reason to happens is that actually, setState is asynchronous. Essentially, we should think of setState as sending a request to React to update the state.

    Imagine that we wanted to be able to get the current value of the state right after it was updated. React allows us to do that, because setState actually takes a second argument, which is a callback function. To use it, we're going to provide a function.

    Inside of this function, I'm going to console log this counter after updating. Now, we have the improved result. Essentially, we see that the counter in render is still equal to one after I click the button, and the counter after updating is equal to one, because this callback fires only after the setState has finished updating the state of our component.