I recently read the react.js documentation and found inconsistencies in setting the state based on previous state value. Here is that chunk of code:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
I thought this way () => this.setState({ count: this.state.count + 1 }) of setting state is wrong and you should use callback for that purpose instead. So I've raised the PR in which I add use of callback function with previous state and it was deprecated because
The callback version is useful when you're not certain what the captured value of state is.
I don't really like when you're not certain part of the explanation and can someone explain why do this way () => this.setState({ count: this.state.count + 1 }) of setting the state is correct.
Thanks in advance.