React – SetState

In React, setState is not guarantee that every time you’d get back the previous state. Take a look below example.

Not good

class App extends React.Component {
  state = {
    counter: 0;
  }
  
  countHandler = () => {
    this.setState({
       counter: this.state.counter + 1
    });
  }
  
}

Better code

class App extends React.Component {
  state = {
    counter: 0;
  }
  
  countHandler = () => {
    this.setState( (previousState, props) => {
       return {
          counter: previousState.counter + 1
       };
    });
  }
  
}

React – SetState

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.