Consider the below example
class MyApp extends Component {
counter = 0;
state = {
counter: 0
};
incrementCounter() {
this.counter = this.counter + 1;
this.setState({
counter: this.state.counter + 1
});
}
render() {
return <div>
<p>{this.counter} and {this.state.counter}</p>
<button onClick={this.incrementCounter}>Increment</button>
</div>
}
}
When I click the button I see both this.counter and this.state.counter are showing the incremented value
My question is why I have to use state? though react is capable of re-rendering all the instance properties
counter = 0;
incrementCounter() {
this.counter = this.counter + 1;
this.setState({});
}
In above snippet, just calling this.setState({}) is doing the trick, then why should I use this.state property for storing my component state?