Enrique Moreno Tent
Enrique Moreno Tent

Reputation: 25237

Different ways to initialize the state in ReactJS

It might be because of the speed that ReactJS is developing, or just some mis-information, but when reading articles about how to set the state, I usually come across different ways.

In the constructor

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { ... }
    }
}

Directly in the class

class MyComponent extends React.Component {
    state = { ... }
}

In ComponentWillMount

class MyComponent extends React.Component {
    ComponentWillMount() {
        this.state = { ... }
    }
}

This diversity of options confuses me often, and makes it hard for me to decide how I should set the state in my components.

My question is: Is there any difference between these methods to set the state? If so, what are the advantages and disadvantages of each?

Upvotes: 0

Views: 64

Answers (3)

Sagiv b.g
Sagiv b.g

Reputation: 31024

These are all basically the same thing, just syntactic sugar.

In the constructor

This is the "normal" standard way to attach a property to a class instance.

Directly in class

This is just a syntactic sugar and this is the class fields proposal which is in stage 3 at the moment (01/10/18). you will need babel/plugin-proposal-class-properties

In ComponentWillMount

Same as the constructor version but inside a life-cycle method of react (which is deprecated by the way).

Upvotes: 1

Estus Flask
Estus Flask

Reputation: 222369

This is class field proposal:

class MyComponent extends React.Component {
    state = { ... }
}

It is syntactic sugar for:

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { ... }
    }
}

The former is shorter and can be considered preferable in transpiled React application because of its brevity, unless there's a need for explicit constructor.

ComponentWillMount lifecycle hook was renamed to UNSAFE_componentWillMount and deprecated in favour of constructor:

UNSAFE_componentWillMount() is invoked just before mounting occurs. It is called before render(), therefore calling setState() synchronously in this method will not trigger an extra rendering. Generally, we recommend using the constructor() instead for initializing state.

Upvotes: 0

Tarek Essam
Tarek Essam

Reputation: 4010

You should now componentWillMount is deprecated and you should not use it. as for setting the state in the constructor or as class property is the same you can use either, I prefer the class property.

Upvotes: 0

Related Questions