React Lifecycle Methods
You have already learnt about two react components, class component and function component. Each component has a lifecycles. Lifecycle is defined as a series of methods that are called at component different phases.There are three phases of react component which are Mounting, Updating and Unmounting.
Mounting is a process in which react component is created and inserted in DOM tree. During mounting phase, four built-in methods are called. The order of calling these methods is given below:-
Except render method, all other methods are optional and are called only if you define them.
In following example, we create initial state number and initialize it with 1.
React elements
It can be single element as <h1> or multiple elements inside <div> node.
React Fragment
You can return multiple elements surrounded by fragement. Fragment lets you to group multiple elements with inserting <div> node.
React Portal
It lets you to render multiple elements in a different DOM sub-tree and return it.
String
You can return simple text as string
Numbers
Numbers can also be returned
Boolean
You can return true or false
Null
You can return nothing
This method is executed only once in component lifecycle that is on first render.
For example, when we change state number to 4 with button onClick event, this is first method to call as
For example, you change state number to 4 in method getDerivedStateFromProps() with a button click. To stop calling render method, just return false in shouldComponentUpdate() method. You will see no change in browser.
This method gets two argument, prevState and prevProps. In this method, you can get props and state before the values were updated. If you define this method, you must have to define another method componentDidUpdate, otherwise there will be an error.
Any value returned by the method is used as third argument by componentDidUpdate method.
Mounting
- React Constructor
- Static getDerivedStateFromProps
- React Render
- React ComponentDidMount
Except render method, all other methods are optional and are called only if you define them.
React Constructor
Constructor is called when component is being initiated (before it is mounted) so it is the suitable place to create and initialize state object. If you need props inside the constructor then call constructor with props as argument. Parent constructor must be called as super(props) to inherit parent class methods.In following example, we create initial state number and initialize it with 1.
class App extends Component{
constructor(props){
super(props);
this.state = {
number: 1
};
}
render(){
return(
<h1>Number is: {this.state.number}</h1>
);
}
}
Output: Number is 1
Static getDerivedStateFromProps
This method is called before render method. This is good place to set state object based on initial props. It takes two arguments, props and state. It returns updated state object. In below example, we change number to 2 and return it.class App extends Component{
constructor(props){
super(props);
this.state = {
number: 1
};
}
static getDerivedStateFromProps(props, state)
{
return { number: 2 };
}
render(){
return(
<h1>Number is: {this.state.number}</h1>
);
}
}
Output: Number is 2
React Render
React Render method is the only required method in class component. It return View in one of following typesReact elements
It can be single element as <h1> or multiple elements inside <div> node.
React Fragment
You can return multiple elements surrounded by fragement. Fragment lets you to group multiple elements with inserting <div> node.
React Portal
It lets you to render multiple elements in a different DOM sub-tree and return it.
String
You can return simple text as string
Numbers
Numbers can also be returned
Boolean
You can return true or false
Null
You can return nothing
React ComponentDidMount
When component is mounted in DOM tree, componentDidMount (component did mount) method is called. This is good place to initiate network request to load data remotely.This method is executed only once in component lifecycle that is on first render.
In below example, initial value of state number in set to 1 in constructor. In method getDerivedStateFromProps, value is changed to 2. Than in method componentDidMount, this state value is set to 3 after 5 second time interval. You can see in browser developer tool.
class App extends Component{
constructor(props){
super(props);
this.state = {
number: 1
};
}
static getDerivedStateFromProps(props, state)
{
return { number: 2 }
}
componentDidMount(){
setTimeout(() => {
console.log(this.state.number);
this.setState({number: 3});
console.log(this.state.number);
console.log('componentDidMount called');
},5000)
}
render(){
return(
<h1>Number is: {this.state.number}</h1>
);
}
}
Output: Number is 3
Updating
When component’s state or props is changed, react update these changes to nodes already in DOM tree. This is updating phase. Following five methods as per given order are called in this phase.- Static getDerivedStateFromProps
- shouldComponentUpdate
- React render
- getSnapshotBeforeUpdate
- componentDidUpdate
static getDerivedStateFromProps
When component’s state or props is updated, this is the first method that is called.For example, when we change state number to 4 with button onClick event, this is first method to call as
class App extends Component{
constructor(props){
super(props);
this.state = {
number: 1
};
}
static getDerivedStateFromProps(props, state)
{
console.log('getDerivedStateFromProps called');
return true;
}
handleClick = () => {
this.setState({number: 4});
}
render(){
return(
<div>
<h1>Number is: {this.state.number}</h1>
<button onClick={this.handleClick}>
Change Value
</button>
</div>
);
}
}
Output: Number is 4
shouldComponentUpdate
this method is invoked before component is re-rendered when new state or props are received. By default, it return true. However, you can skip re-render by returning false. In this case, render method will not be called.For example, you change state number to 4 in method getDerivedStateFromProps() with a button click. To stop calling render method, just return false in shouldComponentUpdate() method. You will see no change in browser.
class App extends Component{
constructor(props){
super(props);
this.state = {
number: 1
};
}
static getDerivedStateFromProps(props, state)
{
console.log('getDerivedStateFromProps called');
return true;
}
shouldComponentUpdate(){
return false;
}
handleClick = () => {
this.setState({number: 4});
}
render(){
return(
<div>
<h1>Number is: {this.state.number}</h1>
<button onClick={this.handleClick}>
Change Value
</button>
</div>
);
}
}
Output: Number is 1
You can observe in google chrome developer tool that state has been changed but not updated in DOM tree.
Render
Render method is called only if componentShouldUpdate returns true. It returns view as per updated state or props.getSnapshotBeforeUpdate
When react detect any change in virtual DOM, it make same changes in browser DOM. This method is called before the browser DOM is actually updated.This method gets two argument, prevState and prevProps. In this method, you can get props and state before the values were updated. If you define this method, you must have to define another method componentDidUpdate, otherwise there will be an error.
Any value returned by the method is used as third argument by componentDidUpdate method.
componentDidUpdate
this method is invoked immediately after the react component is updated in actual DOM. It takes first two parameters as prevState and prevProps. It means that even after the component has been updated in DOM, you can get previous values of props and state. This method takes third parameter returned by getSnapshotBeforeUpdate method. In both methods, getSnapshotBeforeUpdate and componentDidUpdate, if you console state number, it will be 4. However, if you console passed arguments prevState, number value will be 1 as it will show values before update.class App extends Component{
constructor(props){
super(props);
this.state = {
number: 1
};
}
static getDerivedStateFromProps(props, state)
{
console.log('getDerivedStateFromProps is called');
return true;
}
shouldComponentUpdate(){
return true;
}
getSnapshotBeforeUpdate(prevProps, prevState)
{
console.log(this.state.number);
console.log('Prev State: '+prevState.number);
return 20;
}
componentDidUpdate(prevProps, prevState, snapshot)
{
console.log('Prev State: '+prevState.number);
console.log('Snapshot : '+snapshot);
}
handleClick = () => {
this.setState({number: 4});
}
render(){
return(
<div>
<h1>Number is: {this.state.number}</h1>
<button onClick={this.handleClick}>
Change Value
</button>
</div>
);
}
}
Output: Number is 4
Unmounting
Third phase of react component lifecycle is unmounting. This is the process in which components are removed from DOM. Following is the only one method that is called when component is about to be removed from DOM.componentWillUnmount
This method (react component will unmount) is the suitable place to perform any necessary cleanup like cleaning up any subscription, cancelling network requests or invalidating timers.Example:
Create another component Child as
class Child extends Component{
componentWillUnmount(){
console.log('component will unmount is called');
}
render(){
return(
<h1>My Heading</h1>
);
}
}
Now in App.jsx, when you remove heading on button click, componentWillUnmount of child will be called before unmounting as
class App extends Component{
constructor(props){
super(props);
this.state = {
show: true
};
}
removeHeading = () => {
this.setState({show: false});
}
render(){
let heading;
if(this.state.show){
heading = <Child />;
}
return(
<div>
{heading}
<h1>Number is: {this.state.number}</h1>
<button onClick={this.removeHeading}>
Remove Heading
</button>
</div>
);
}
}
إرسال تعليق