React: Questions and Answers

What is the difference between using constructor vs getInitialState?

When using ES6 classes then you should initialize state in the constructor

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

Note:
– this.state is assigned directly in the constructor, but everywhere else use this.setState()
– you cannot use getInitialState() with ES6 class

Define the getInitialState method when using React.createClass.

var MyComponent = React.createClass({
 getInitialState() {
 return { /* initial state */ };
 },
});

Reference

Rules:
Component name starts with a capital letter
Components must return a single root element.
Props are readonly