Guy
Guy

Reputation: 13286

Initializing state in constructor versus state

What is the difference between those two ways to set initial state in ES6 besides the access to the props?

constructor(props) {
    super(props);

    this.state = {
        highlighted: 5,
        backgroundColor: '#f3f3f3', 
    }
}

vs:

 state = {
        highlighted: 5,
        backgroundColor: '#f3f3f3',
    }

Upvotes: 1

Views: 54

Answers (1)

Jonny Buchanan
Jonny Buchanan

Reputation: 62793

The former is just syntax suger for the latter, so access to constructor arguments really is the only difference.

This is how it gets transpiled by Babel using only babel-preset-stage-2 preset to handle the proposed class properties syntax:

class Example {
  state = {
    highlighted: 5,
    backgroundColor: '#f3f3f3',
  }
}

Output:

class Example {
  constructor() {
    this.state = {
      highlighted: 5,
      backgroundColor: '#f3f3f3'
    };
  }
}

This is also why declaring a function using a class property arrow function binds it to the instance.

It gets moved into the constructor, where the this value the arrow function preserves is the new instance.

class Example {
  boundFunction = () => {
    // ...
  }
}

Output:

class Example {
  constructor() {
    this.boundFunction = () => {
      // ...
    };
  }
}

Upvotes: 3

Related Questions