DEV Community

Christina Gaitán
Christina Gaitán

Posted on

React - Updating self-dependent state

In React, sometimes we need to update a state value taking into account the current state.

For example, if we are writing a Poll app and we have a button or another component to update the number of votes, we can do something like this:

incrementVotes = () => {
  const currentVotes = this.state.votes;
  this.setState({
    votes: currentVotes + 1
  });
};

The above code could work, but considering that setState() is an asynchronous function, a better solution is to send a function to setState() as follows:

  incrementVotes = () => {
    this.setState(prevState => {
      return {
        votes: prevState.votes + 1
      };
    });
  };

Update

With the first approach, we have the risk that our state does not update immediately, for example if our votes count is 10 and we have a user that is too fast clicking the button, we could have two calls to incrementVotes() in which the value of this.state.votes is the same and in the end we have a final value of 11 when the correct value should be 12.

Maybe there is a thin probability of this occurring but this is a good way of protecting our application of this kind of bugs.

Top comments (3)

Collapse
 
deanius profile image
Dean Radcliffe

Great bite-sized post! But I think you should explain why it's better - in other words - when does it not work?

Collapse
 
christinagaitan profile image
Christina Gaitán

Thank you!, I just updated the post to add an explanation.

Collapse
 
deanius profile image
Dean Radcliffe

Nice edit! 😆