Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

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

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    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.

    reactReact
    javascriptJavaScript
    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
    Transcript

    Transcript

    Instructor: 00:00 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.

    00:15 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.

    00:35 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.

    00:55 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.

    01:09 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.

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

    Discuss

    Discuss