Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've seen both used interchangeably.

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

like image 855
Nader Dabit Avatar asked Jun 05 '15 13:06

Nader Dabit


People also ask

Why we use constructor in React native?

In React, constructors are mainly used for two purposes: It used for initializing the local state of the component by assigning an object to this. state. It used for binding event handler methods that occur in your component.

What is getInitialState in React?

getInitialState is the ES5 friendly method to define the initial state of a React component. JavaScript React. One fairly popular question that got asked on programming bulletin boards has to do with the similarities and differences between React's constructor and the built in method getInitialState .

What is the difference between constructor and componentDidMount?

You can use the constructor method or componentDidMount depending on what you need to be done. constructor will be called pre-render and componentDidMount post-render. The componentWillMount method is called right before a component mounts or the render method is called.

How do I use a constructor in React native?

In React, the constructor is called during component creation and before mounting. If you want to implement the constructor for a React component, call the super(props) method before any other statement. Otherwise, this. props will be undefined in the constructor and create bugs.


1 Answers

The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the getInitialState method when using React.createClass.

See the official React doc on the subject of ES6 classes.

class MyComponent extends React.Component {   constructor(props) {     super(props);     this.state = { /* initial state */ };   } } 

is equivalent to

var MyComponent = React.createClass({   getInitialState() {     return { /* initial state */ };   }, }); 
like image 176
Alexandre Kirszenberg Avatar answered Oct 09 '22 05:10

Alexandre Kirszenberg