I came across some react code that defined a component state inside a class like follows:
// Snippet 1
class Sample extends React.Component {
state = {
count: 0
}
}
The way I've learnt React was to declare the state inside the constructor of a class:
// Snippet 2
class Sample extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
}
The only difference I can think of is that initializing the state in the constructor would guarantee the state gets initialized properly in the component life cycle.
What are the differences between the above two code snippets? In snippet 1, is it safe to assume that the state be properly set when the class is initialized?
Initializing state In class components, there are two ways to initialize state — in a constructor function or as a Class property. Constructor functions, introduced in ES6, is the first function called in a class when it is first instantiated — meaning when a new object is created from the class.
There are two ways to initialize state in a React component: inside the constructor, and directly inside the class.
The obvious constructor One obvious place to initialize is the constructor of the component. Similar to the following: class Contacts extends React.
To declare state using React Hooks, we need to use the useState hook. The useState hook accepts a parameter which is the initial value of the state. In class-based components, state is always an object.
What you're looking at is ES7+ Property Initializers
. It is done this way because Facebook knows Javascript will change in the future. They want to be able to cope with those changes.
According to facebook ES7+ Property Initializers
Wait, assigning to properties seems like a very imperative way of defining classes! You're right, however, we designed it this way because it's idiomatic. We fully expect a more declarative syntax for property initialization to arrive in future version of JavaScript....
Here is the Facebook link Also more info here
also a Link to the proposal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With