Whenever a change is made to the state
or props
of a React component, the component get updated. This is called updating phase of the React component lifecycle.
- static getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
1. static getDerivedStateFromProps()
- 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. shouldComponentUpdate()
Within this lifecycle method, you can return a boolean — true
or false
— and control whether the component gets rerendered
3. render()
The render()
method is the only required method in a class component. render() will not be invoked if shouldComponentUpdate() returns false.
4. getSnapshotBeforeUpdate()
The getSnapshotBeforeUpdatelifecycle method stores the previous values of the state after the DOM is updated. getSnapshotBeforeUpdate() is called right after the render method.
5. componentDidUpdate
componentDidUpdate()
is called after componentDidMount()
and can be useful to perform some action when the state changes.componentDidUpdate()
takes as its first two arguments the previous props and the previous state.
Example.
import React, { Component } from 'react' class LifeCycleA extends Component { constructor(props) { super(props) this.state = { name : 'Amey ' } console.log(" 1 - A Constructor"); } static getDerivedStateFromProps(nextProps, prevState) { console.log("2- A getDerivedStateFromProps") return null; } componentDidMount() { console.log("4 - A componentDidMount") } shouldComponentUpdate(){ console.log("5 - A shouldComponentUpdate") return true; } getSnapshotBeforeUpdate(prevProps, prevState){ console.log("6 - A getSnapshotBeforeUpdate") return null; } componentDidUpdate(){ console.log("7 - A componentDidUpdate") } chageState = () => { this.setState({ name: 'raut' }) } render() { console.log("3 -A reders") return ( <div> Hello <button onClick={this.chageState}> change</button> </div> ) } } export default LifeCycleA;