Life Cycle of a Component


 A component life cycle is divided into Initialization, Mounting, Update, and UnMounting stages.
Here is a detail explanation about each Component.

A component in reactjs has the following stages :

Initialization: This is the first stage of the component life cycle.
Here it will have the default props and the state at the initial level.

Mounting: In this phase, the Component is rendered inside the dom. We having exposure to following methods in the mounting state.

componentDidMount(): This is also called when the Component is just added to the dom.

render(): You have this method for all the components created. It returns the Html node.

Update: In this state, the dom is interacted by a user and updated. For example, you enter something in the textbox, so the state properties are updated.

Following are the methods available in update state:

shouldComponentUpdate() : called when the component is updated.
componentDidUpdate() : after the component is updated.
UnMounting: this state comes into the picture when the Component is not required or removed.
Following are the methods available in unmount state:
Component willUnmount(): called when the Component is removed or destroyed.
Working Example
Here is a working example which shows the methods called at each state.
Example: complife.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class COMP_LIFE extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: ''};
    this.UpdateName = this.UpdateName.bind(this);
    this.testclick = this.testclick.bind(this);
  }
  UpdateName(event) {
    this.setState({name: event.target.value});
  }
  
  testclick(event) {
    alert("The name entered is: "+ this.state.name);
  }
  
  componentDidMount() {  
    console.log('Mounting State : calling method componentDidMount');
  }   
 
  shouldComponentUpdate() {  
    console.log('Update  State : calling method shouldComponentUpdate');
    return true;
  }  
  componentDidUpdate() {  
    console.log('Update  State : calling method componentDidUpdate')  
  }  
  componentWillUnmount() {  
    console.log('UnMounting State : calling method componentWillUnmount');
  }  
  render() {
    return (
      <div>        
         Enter Your Name:<input type="text" value={this.state.name} onChange={this.UpdateName} /><br/>        
        <h2>{this.state.name}</h2>
        <input type="button" value="Click Here" onClick={this.testclick} />
      </div>
    );
  }
}
export default COMP_LIFE;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import COMP_LIFE from './complife.jsx';
ReactDOM.render(
    <COMP_LIFE />,
    document.getElementById('root')
); 
When you check the output in the browser

In browser console you get :


When the user enters in the textbox :

In console following messages are displayed:

No comments:

Post a Comment