Pass a function to setState in React

Share this video with your friends

Social Share Links

Send Tweet

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.

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.