EDIT: This question isn't a duplicate as far as I can see, because the issue isn't whether to use arrow functions or not, it is whether or not using a constructor, even though not required when using arrow functions, is more performant, or cleaner syntax, or best practice. I am confused as to when to use the constructor and when not to, as I have never needed to use one, nor was I taught that it was ever necessary. This is the issue I am trying to clarify, and I have not been able to after significant effort.
I have googled around quite a bit, and haven't quite been able to find the answer to my question. When I learned React recently, I was taught to write a component like this, with no constructor:
class App extends React.Component {
state = {
color: "green"
}
changeColor = () => {
if (this.state.color === "green"){
this.setState({color: "yellow"})
} else {
this.setState({color: "green"})
}
render() {
return(
<div>
<h1 style={{color: this.state.color}}>What color am I?</h1>
<button className='btn btn-default' onClick={this.changeColor}>Change Color</button>
</div>
)
}
}
Where the arrow function binds the context of "this". This code runs just fine, but every tutorial I see, every video I watch, every bit of other people's code I see has it written like this:
class App extends React.Component {
constructor(props){
super(props)
this.state={
color: "green"
}
this.changeColor = this.changeColor.bind(this);
}
changeColor(){
if (this.state.color === "green"){
this.setState({color: "yellow"})
} else {
this.setState({color: "green"})
}
render() {
return(
<div>
<h1 style={{color: this.state.color}}>What color am I?</h1>
<button className='btn btn-default' onClick={this.changeColor}>Change Color</button>
</div>
)
}
}
What I am curious about is whether there is a benefit to using the constructor, or is the first example a better way to do it? Are there pitfalls I am not aware of with doing this the way I am doing? Any help would be greatly appreciated.