Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between using constructor vs state = {} in React / React Native? [duplicate]

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?

like image 228
David Schumann Avatar asked Mar 01 '18 13:03

David Schumann


People also ask

What is the difference between using constructor vs getInitialState in React?

The constructor and getInitialState both in React are used to initialize state, but they can't be used interchangeably. The difference between these two is we should initialize state in the constructor when we are using ES6 classes and define the getInitialState method when we are using React. createClass (ES5 syntax).

What does constructor do in React native?

constructor() Typically, in React constructors are only used for two purposes: Initializing local state by assigning an object to this.state . Binding event handler methods to an instance.

Can we use state without constructor in React?

You can also use state in React function components (without a constructor), but using higher-order components or render prop components.

Why should you avoid copying the values of props into a component's state?

Don't “copy props into state.” It creates a second source of truth for your data, which usually leads to bugs. One source of truth is best. Components will already re-render when their props change, so there's no need to duplicate the props as state and then try to keep it up to date.


1 Answers

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,
  }
}
like image 133
Piyush Dhamecha Avatar answered Oct 13 '22 12:10

Piyush Dhamecha