PDA

View Full Version : State the difference between getIntialState() and constructor()?



adulistravel
04-30-2020, 10:43 PM
State the difference between getIntialState() and constructor()?

sinelogixtech
05-04-2020, 04:23 AM
Hi Friends,
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.

Akshay_M
05-05-2020, 05:42 PM
The difference between constructor and getInitialState is the difference between ES6 and ES5 itself.
getInitialState is used with React.createClass and
constructor is used with React.Component.

Hence the question boils down to advantages/disadvantages of using ES6 or ES5.

Let's look at the difference in code

ES5

var TodoApp = React.createClass({
propTypes: {
title: PropTypes.string.isRequired
},
getInitialState () {
return {
items: []
};
}
});

ES6

class TodoApp extends React.Component {
constructor () {
super()
this.state = {
items: []
}
}
};