Amous
Amous

Reputation: 514

Initializing react component state

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?

Upvotes: 7

Views: 1933

Answers (2)

mrdotb
mrdotb

Reputation: 652

It's just a syntactic sugar to make Class look cleaner already on babel: https://babeljs.io/docs/plugins/transform-class-properties/

Upvotes: 0

Train
Train

Reputation: 3496

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

Upvotes: 5

Related Questions