0

I'm new to React and I'm writing a simple class and trying to figure out where is the best place to initialize the state, should I do it in a constructor like this:

Class Quotes extends Component {
    constructor(props) {
        super(props);
        this.state = {
            color: 'blue'
        };
   }
...

Or as a state property like this:

Class Quotes extends Component {
state = {
    color: 'blue'
  };
...

Which one is better practice? and what are the advantages and disadvantages of both?

Moses Schwartz
  • 2,857
  • 1
  • 20
  • 32

2 Answers2

3

Both are correct uses of initialising state. I would recommend to use constructor when you want to build a state using props otherwise go with other pattern.

export default class Person extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      name: props.name || 'User',
    }
  }
}

When props is not required for initialization

export default class Person extends PureComponent {
  state = {
    name: 'User',
  }
}
Milind Agrawal
  • 2,724
  • 1
  • 13
  • 20
-1

Its good to initialize state inside constructor like so whenever your component is initializing it will give default state to component

Class Quotes extends Component {
    constructor(props) {
        super(props);
        this.state = {
            color: 'blue'
        };
   }
}
Puneet Bhandari
  • 337
  • 5
  • 14