What is component lifecycle in React
In this chapter, you will learn about component lifecycle in React JS. I suggest you do not skip this chapter, as a react developer it is very important to understand how component lifecycle executes in the React JS. Note that the component lifecycle methods can only be accessed in the class-based component.
How class-based component lifecycle gets executed in React?
Before understanding how lifecycle gets executed, let’s list the methods which come under the lifecycle. We can use the below methods in the class-based components in order to get some data from REST API, remove the component, or updating the component and much more. In component lifecycle, the below methods can run in a different time. These methods will get executed when a component is created first time or component is been updated. Now let’s see in which order the methods will get executed.
- constructor()
- getDerivedStateFromProps()
- getSnapshotBeforeUpdate()
- componentDidCatch()
- componentDidUpdate()
- componentWillUnmount()
- shouldComponentUpdate()
- componentDidUpdate()
- componentDidMount()
- render()
The component lifecycle has 3 phases which some of the methods get executed in specific phases. There are 3 phases in the component lifecycle, and they are
- Mounting or creation
- Updating
- Unmounting.
Component mounting or creation lifecycle:
In this section first, we will understand how creation phase run, let’s see how the lifecycle of component creation works.
constructor():
The constructor will get executed as the component is created. And it receives the props of the component, we call the super props in the constructor. Here note that constructor will run automatically even if you don’t define one. Its good creates constructor when you wish to initialize your own logic in the constructor. In this hook make sure that you should not make any HTTP requests.
getDerivedStateFromProps():
Once the execution of constructor is been finished, then the getDerivedStateFromProps method will get executes. Whenever the class-based component props get change, you can sink your state to them. This is a very rare case.
render():
After the constructor and getDerivedStateFromProps, the render() method will run. As we used it in your previous chapters, it just returns the JSX. Here there will be an app component that we specify in the index.js and after that, we mention the child components, the child components also get rendered here. Once all the child components get rendered, then componentDidMount() method will run.
componentDidMount():
The componentDidMount() hook method is very important in the component lifecycle. We use this method frequently in the class-based application in the javascript event-driven applications. Here you can make HTTP requests to get the new data from the server.
Now let’s see the practical example for component lifecycle
Let’s create a class-based component app.js, and functional component employee.js. We will refer to the employee login module that we learned in the previous chapter. Follow the below getDerivedStateFromProps
Step 1:
Create the file src/Employee/Employee.js if you have it already paste the below code snippet.
import React from 'react'; const employee = (props) => { console.log('Rendering the employee component...'); return ( <div> { props.isEmployeeLoggedIn ? <div> <h2>Welcome to your dashboard</h2> <button onClick = { props.logout }>Logout</button> </div> : <div> <h2>Your session has been expired, please login to access</h2> <button onClick = { props.login }>Login</button> </div> } </div> ) } export default employee;
Steps 2:
Create the file src/App.js if you have it already paste the below code snippet.
import React, { Component } from 'react'; import './App.css'; import Employee from './Employee/Employee' class App extends Component { constructor(props) { console.log('Calling the constructor method...'); super(props); this.state = { isLoggedIn: false }; this.login = this.login.bind(this); this.logout = this.logout.bind(this); } login = (e) => { console.log('Calling the login method...'); this.setState({ isEmployeeLoggedIn: true }); } logout = (e) => { console.log('Calling the logout method...'); this.setState({ isEmployeeLoggedIn: false }); } render() { console.log('Calling the render method...'); return ( <div className="App"> <h1>Welcome to react JS tutorial</h1> <Employee isEmployeeLoggedIn={this.state.isEmployeeLoggedIn} login = {this.login } logout = { this.logout} /> </div> ); } } export default App;
Now we will see the output, that we have used the console to log the details.
console output for the lifecycle of component creation
Running the constructor method... Running the getDerivedStateFromProps method... Running the render method... Rendering the employee component... Running the componentDidMount method...
Component update lifecycle:
As we learned, whenever state or props change the React re-renders the DOM, now it has a different lifecycle and let’s see which methods will get executed first.
getDerivedStateFromProps():
the component update lifecycle starts with the method getDerivedStateFromProps(). State and props will be updated based on the outside changes.
shouldComponentUpdate():
After getDerivedStateFromProps runs, then the method shouldComponentUpdate method runs. This method helps in cancelling the update process, here you can decide whether to render element or not.
render():
Now render method will render the components as well the child component with new props received.
getSnapshotBeforeUpdate();
After rendering the components, the getSnapshotBeforeUpdate method will get executed. This lifecycle hook accepts the previous props and state as an input.
Now if you click on the login button, we are updating the state isEmployeeLoggedIn. Let’s see the console
Running the login method... Running the getDerivedStateFromProps method... Running the render method... Rendering the employee component...
The component lifecycle of unmounting:
This method is called when a component is being removed from the DOM: componentWillUnmount()
One thought on “What is component lifecycle in React”
Comments are closed.