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