These methods are called in the following order when an instance of a component is being created and inserted into the DOM
- constructor()
- static getDerivedStateFromProps()
- render()
- componentDidMount()
1. constructor()
- It used for initializing the local state of the component by assigning an object to this.state.
- It used for binding event handler methods that occur in your component.
- You cannot call setState() method directly in the constructor()
- Do not use constructor for API Calls
Constructor(props){
super(props);
}
2. static getDerivedStateFromProps()
getDerivedStateFromProps is used whenever you want to update state before render and update with the condition of props
GetDerivedStateFromPropd updating the stats value with the help of props value
it is static method so we can not use this key word to call this method
3. render()
The render()
method is the only required method in a class component.
render()
will not be invoked if shouldComponentUpdate()
returns false.
4.componentDidMount()
componentDidMount()
is invoked immediately after a component is mounted
where you can apply side effects, for example, getting data from server.
Example.
import React, { Component } from 'react' class LifeCycleA extends Component { constructor(props) { super(props) this.state = { name : 'User' } console.log(" 1 - A Constructor"); } static getDerivedStateFromProps(nextProps, prevState) { console.log("2- A Drivestate") return null; } componentDidMount() { console.log("4 - A componentDidMount") } render() { console.log("3 -A render") return ( <div> Hello </div> ) } } export default LifeCycleA;