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 (4)

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! 😆

Collapse
 
wanzulfikri profile image
wanzulfikri

Does that mean, in the second approach, two calls to setState will run sequentially rather than simultaneously? A race condition of sorts.

16 Libraries You Should Know as a React Developer

Being a modern React developer is not about knowing just React itself. To stay competitive, it is highly recommended to explore the whole ecosystem. This article contains some of the most useful React component libraries to speed up your developer workflow.