React Component Lifecycle
When a React component is created, a number of functions are called:
If you are using React.createClass (ES5), 5 user defined functions are called
If you are using class Component extends React.Component (ES6), 3 user defined functions are called getDefaultProps() (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:
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:
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.
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.
) or a composite component. If nothing should be rendered, it can return null or undefined.
This function will be recalled after any change to the component's props or state.
componentDidMount() (ES5 and ES6)
This is the fifth method called.
The component has been mounted and you are now able to access the component's DOM nodes, e.g. via refs.
This method should be used for:
.Adding event listeners
.Manipulating DOM elements
If the component is defined using ES6 class syntax, the functions getDefaultProps() and getInitialState() cannot be used.
Instead, we declare our defaultProps as a static property on the class, and declare the state shape and initial state in the constructor of our class. These are both set on the instance of the class at construction time, before any other React lifecycle function is called.
The following example demonstrates this alternative approach:
Default values for the component props are specified by setting the defaultProps property of the class:
The idiomatic way to set up the initial state of the component is to set this.state in the constructor: