React – SetState

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
       };
    });
  }
  
}

Write a Reply or Comment

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