Home >>ReactJS Tutorial >ReactJS Component Life Cycle

ReactJS Component Life Cycle

ReactJS Component Life Cycle

Lifecycle Methods

  1. ComponentWillMount is executed on both the server and client side, before rendering.
  2. ComponentDidMount is only executed on the client side after first render. This is where AJAX requests should occur, as well as DOM or state updates. This method is also used for integration with other JavaScript frameworks and any functions such as setTimeout or setInterval with delayed execution. We use it to update the state so we can activate the other methods in the lifecycle.
  3. ComponentWillUpdate is called immediately prior to rendering.
  4. ComponentDidUpdate is called immediately after a render.
  5. ComponentWillUnmount is named after unmounted component from the dom. In main.js we unmount our component.
  6. Should ComponentUpdate return the values true or false. That will determine whether or not the component will be updated. By default, that is set to real. If you are sure the component doesn't need to render after updating the state or props, you can return the false value.

We'll set the initial state in the constructor function in the following example. Uses the setNewn number to update the state. All lifecycle methods are within the component Content.

App.jsx

import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
      
      this.state = {
         data: 0
      }
      this.setNewNumber = this.setNewNumber.bind(this)
   };
   setNewNumber() {
      this.setState({data: this.state.data + 1})
   }
   render() {
      return (
         <div>
            <button onClick = {this.setNewNumber}>Click me to Increament Number</button>
            <Content myNumber = {this.state.data}></Content>
         </div>
      );
   }
}
class Content extends React.Component {
   componentWillMount() {
      console.log('Component WILL MOUNT!')
   }
   componentDidMount() {
      console.log('Component DID MOUNT!')
   }
   componentWillReceiveProps(newProps) {    
      console.log('Component WILL RECIEVE PROPS!')
   }
   shouldComponentUpdate(newProps, newState) {
      return true;
   }
   componentWillUpdate(nextProps, nextState) {
      console.log('Component WILL UPDATE!');
   }
   componentDidUpdate(prevProps, prevState) {
      console.log('Component DID UPDATE!')
   }
   componentWillUnmount() {
      console.log('Component WILL UNMOUNT!')
   }
   render() {
      return (
         <div>
            <h3>{this.props.myNumber}</h3>
         </div>
      );
   }
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

setTimeout(() => {
ReactDOM.unmountComponentAtNode(document.getElementById('app'));}, 10000);

We will get the following Output

Output

reactjs Component Life Cycle