Become a member
to unlock all features

Level Up!

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


    Pass a function to setState in React

    Alex Jover MoralesAlex Jover Morales

    In React, when you want to set the state which calculation depends on the current state, using an object can lead to state inconsistency. This is due to the fact that React can batch multiple state changes for performance reasons.

    This lesson shows you how using a function in setState can solve that.



    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




    Instructor: I have here a very simple app component with a state with the count property which is displayed down here, and a button which has on click event with a count by three method.

    Count by three is still not implemented. Let's do it. We use setState to modify the state and we'll say count: this.state.count+1. We are going to duplicate this two more times, so they made up a count of three.

    When we try this out and you press count, you will see that this just summing up one. This is maybe not what you expect, and the reason is that React doesn't only update the state when you call setState, but also performs all kind of heavy operations to make sure the state matches the UI.

    That process is now has reconciliation. A React combat several state update for performance. Keep in mind that this problem only happens when you are setting the state based on a previous state.

    Back to the code, just remove those two lines. In order to solve this, instead of passing an object to set a state, let's pass a function that has a state as a parameter, and returns a count just as before, but now it's taken the count from the state passed as a parameter. Let's duplicate this two more times again.

    We'll try this out. We'll see that the count is summing up by three which is now what we want.