When a React component is created, a number of functions are called:
React.createClass (ES5), 5 user defined functions are calledclass Component extends React.Component (ES6), 3 user defined functions are calledgetDefaultProps() (ES5 only)This is the first method called.
Prop values returned by this function will be used as defaults if they are not defined when the component is instantiated.
In the following example, this.props.name will be defaulted to Bob if not specified otherwise:
getDefaultProps() {
return {
initialCount: 0,
name: 'Bob'
};
}
getInitialState() (ES5 only)This is the second method called.
The return value of getInitialState() defines the initial state of the React component. The React framework will call this function and assign the return value to this.state.
In the following example, this.state.count will be intialized with the value of this.props.initialCount:
getInitialState() {
return {
count : this.props.initialCount
};
}
componentWillMount() (ES5 and ES6)This is the third method called.
This function can be used to make final changes to the component before it will be added to the DOM.
componentWillMount() {
...
}
render() (ES5 and ES6)This is the fourth method called.
The render() function should be a pure function of the component’s state and props. It returns a single element which represents the component during the rendering process and should either be a representation of a native DOM component (e.g. <p />) or a composite component. If nothing should be rendered, it can return null or undefined.