1

In a JS class what's the difference between:

class MyClass extends components {
    constructor(props) {
        super(props);
        this.state = {toto:"toto"}
    }
}

and

class MyClass extends components {
    state = {toto:"toto"}
}

[Edit] It's the same: Thanks for your answers !

Ben Grandin
  • 129
  • 1
  • 5
  • 2
    There's no difference. – Pointy Jan 09 '20 at 14:08
  • Does this answer your question? [When is it appropriate to use a constructor in REACT?](https://stackoverflow.com/questions/53022332/when-is-it-appropriate-to-use-a-constructor-in-react) – Ali Mousavi Jan 09 '20 at 14:09
  • 1
    The second way is new and not yet *Finished* ([Class field declarations proposal](https://github.com/tc39/proposal-class-fields)). One small difference is, in the second way, you can't use the parameter from constructor in the declaration. – adiga Jan 09 '20 at 14:11
  • 1
    "*if someone know why Webstorm order my state in after render method*" - that's a separate question which should be posted separately, but it looks like you configured your IDE to sort class members alphabetically (with the constructor at the top)? – Bergi Jan 09 '20 at 14:15
  • @Bergi I configure it well, he put the constructor, then my fields then property and method. Only the state fields is last.. It's doesn't happen in a other project – Ben Grandin Jan 09 '20 at 14:22

2 Answers2

2

Declaring state like this without a constructor:

state = {}

Is called class fields, TC39 proposal currently on stage 3 last I checked, but it has wide spread adoption in the React community.

Basically it isn't currently part of javascript, but compilers such as babel allow this syntax and will compile it into valid javascript code.

Travis James
  • 1,879
  • 9
  • 22
1

No difference, its just a syntactic sugar

Daijoubu
  • 44
  • 2