In all react tutorials that i have seen, variables which are responsible for changing the content of the component are kept in state object and calling setState() method updates those variables and re-renders the page. From further reading it seemed that only function of this setState() method was to re-render the page
My Question is if setState() is just used for re-rendering why not just keep the state object empty, declare all your dynamic content changing variables as class attributes like you normally do and call this.setState({}) whenever you want to re-render.
So what is the use of keeping variables inside state object? When does above technique fail?
example instead of:
class Button1 extends Component {
constructor() {
super();
this.state = {
counter: 0,
};
}
incrementCounter = () => {
this.setState({counter:this.state.counter+1,message:""})
};
render() {
return (
<div>
<button onClick={()=>{this.incrementCounter()}}> Click </button>
<p>{this.state.counter}</p>
</div>
);
}
}
i could do:
class Button2 extends Component {
constructor() {
super();
this.counter=0;
}
refresh(){
this.setState({});
}
incrementCounter = () => {
this.counter+=1;
this.refresh();
};
render() {
return (
<div>
<button onClick={()=>{this.incrementCounter()}}> Click </button>
<p>{this.counter}</p>
</div>
);
}
}
i personally like 2nd approach? What are its pitfalls?