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: []
}
}
};
There is an interesting reddit thread regarding this.
React community is moving closer to ES6. Also it is considered as the best practice.
There are some differences between React.createClass
and React.Component
. For instance, how this
is handled in these cases. Read more about such differences in this blogpost and facebook's content on autobinding
constructor
can also be used to handle such situations. To bind methods to a component instance, it can be pre-bonded in the constructor
. This is a good material to do such cool stuff.
Some more good material on best practices
Best Practices for Component State in React.js
Converting React project from ES5 to ES6
Update: April 9, 2019,:
With the new changes in Javascript class API, you don't need a constructor.
You could do
class TodoApp extends React.Component {
this.state = {items: []}
};
This will still get transpiled to constructor format, but you won't have to worry about it. you can use this format that is more readable.
With React Hooks
From React version 16.8, there's a new API Called hooks.
Now, you don't even need a class component to have a state. It can even be done in a functional component.
import React, { useState } from 'react';
function TodoApp () {
const items = useState([]);
Note that the initial state is passed as an argument to useState
; useState([])
Read more about react hooks from the official docs