Should we include the `props` parameter to class constructors when declaring components (using ES6 classes)?


(Sergio Cruz) #1

The following example is in the docs, which includes props as a parameter to the class’ constructor function.

export class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
  }
  //...
}

Source: https://facebook.github.io/react/docs/reusable-components.html#es6-classes

I have been declaring components without declaring the props parameter and it seems like components still behave the same.

Is there a difference in behavior between using both syntaxes? Which syntax is best recommended?

Thanks :smile:


Constructor(props) and super(props) VS constructor() and super()
(Sophie Alpert) #2

If you want to use this.props in the constructor, you need to pass props to super. Otherwise, it doesn’t matter because React sets .props on the instance from the outside immediately after calling the constructor.


(Sergio Cruz) #3

Thanks that makes a lot of sense :slight_smile:


(Milesj) #4

I’m assuming the same applies to the context? Since the constructor is actually props, context, updater.


(Sophie Alpert) #5

Yes, that’s right.


(Minkesh) #6

I could not get what do you mean by the context ? Beacuse ‘this’ we use anyways without passing ‘context’ to the super. Or is it implicitly passed ?


(Jesse McCarthy) #7

@minkesh They don’t mean the context, they mean the React context feature and a constructor param called context that’s part of it. See https://github.com/facebook/react/issues/6186.


(Minkesh) #8

@Jmm, thanks for the explanation and it is more clear now :slightly_smiling: