Is there any difference of declaring state
, out of constructor?
I have an example of a component here:
class BurgerBuilder extends Component {
state = {
ingredients: {
salad: 0,
bacon: 0,
cheese: 0,
meat: 0
},
totalPrice: 30
};
....
}
Here I just declare a variable called state, which includes the variables of the component, but I don't call a constructor.
Where as i declare:
class BurgerBuilder extends Component {
constructor() {
super();
this.state = {
ingredients: {
salad: 0,
bacon: 0,
cheese: 0,
meat: 0
},
totalPrice: 30
};
}
....
}
I found, that I can use this.setState
for both solutions and that there is no real difference in my project. Is there a best practice, on what to use where.
Is there any difference? Is there a best practice, on what to use where?
They're almost the same. The syntax for declaring the state
without contructor()
is syntactic sugar.
What you're using in the first example is called Class field declarations. (This proposal reached Stage 3 in July 2017).
In short, this proposal allows us a simpler syntax for declaring class fields, without the need for the constructor()
.
For example, those codes are written using ES2015
class Counter extends HTMLElement {
constructor() {
super();
this.onclick = this.clicked.bind(this);
this.x = 0;
}
clicked() {
this.x++;
window.requestAnimationFrame(this.render.bind(this));
}
connectedCallback() { this.render(); }
render() {
this.textContent = this.x.toString();
}
}
window.customElements.define('num-counter', Counter);
By using Class field declarations, they will be like this:
class Counter extends HTMLElement {
x = 0;
clicked() {
this.x++;
window.requestAnimationFrame(this.render.bind(this));
}
constructor() {
super();
this.onclick = this.clicked.bind(this);
}
connectedCallback() { this.render(); }
render() {
this.textContent = this.x.toString();
}
}
window.customElements.define('num-counter', Counter);
The benefits of using this syntax:
By declaring fields up-front, class definitions become more self-documenting; instances go through fewer state transitions, as declared fields are always present.
Reference: Class field declarations for JavaScript
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