6

I have seen both

export default class LoginScreen extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      loading: false,
      loggedIn: false,
    }
  }
}

and

export default class LoginScreen extends React.Component {
  state = {
    loading: false,
    loggedIn: false,
  }
}

What are the use cases for both? Are there advantages / disadvantages? Is one a better practice?

David Schumann
  • 13,380
  • 9
  • 75
  • 96

2 Answers2

13

Use constructor when you want to save props data into state

export default class LoginScreen extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      loading: props.loading,
      loggedIn: props.loggedIn,
    }
  }
}

Otherwise you can directly set the state for hard coded data

export default class LoginScreen extends React.Component {
  state = {
    loading: false,
    loggedIn: false,
  }
}
Piyush Dhamecha
  • 1,485
  • 1
  • 13
  • 22
  • Copying props into state is considered an anti pattern by the official docs: https://reactjs.org/docs/react-component.html#constructor – Remi Jul 22 '19 at 09:09
  • @Remi Please read this para `Only use this pattern if you intentionally want to ignore prop updates.`, you can store props to state for default or initial value. – Piyush Dhamecha Jul 26 '19 at 15:38
0

The performance is same in both the cases so it's just a matter of personal preference. Defining state outside of class happens to be a newer implementation than defining it inside a constructor so I would suggest you use explicit state definition.

Nagarjun Prasad
  • 802
  • 3
  • 17
  • 31