I found there is two way to declare state in class component like below
class App extends Component {
constructor(props) {
super(props);
this.state = {
name: 'John'
}
}
render() {
return <div>{this.state.name}</div>
}
}
and
class App extends Component {
state = {
name: 'John'
}
render() {
return <div>{this.state.name}</div>
}
}
What is the difference between these two?
They are roughly equivalent. The significant difference is that the initializer in the second example is executed before
constructor
.The second approach uses class fields proposal.
It is not a part of ECMAScript standard yet so you need to set up transpiler properly to use the second approach.
UPD Take a look at Babel output to better understand how public instance fields work.