Become a member
to unlock all features

Level Up!

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


    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:

    this.setState({counter: 5});

    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.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    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.