Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 838
Amous Avatar asked Dec 14 '16 01:12

Amous


People also ask

How do you initialize a state in React component?

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.

Where do I initialize a state?

There are two ways to initialize state in a React component: inside the constructor, and directly inside the class.

Where is the best place to initialise React components?

The obvious constructor One obvious place to initialize is the constructor of the component. Similar to the following: class Contacts extends React.

How do you declare a state in 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.


1 Answers

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

like image 52
Train Avatar answered Sep 22 '22 03:09

Train