component lifecycle code example

Example 1: lifecycle methods react

Every component in React goes through a lifecycle of events. I like to think of them as going through a cycle of birth, growth, and death.

MountingBirth of your component
UpdateGrowth of your component
UnmountDeath of your component

Example 2: react lifecycle example

class Test extends React.Component {
  constructor() {
    console.log('Constructor')
    super();
    this.state = {
      count: 0
    };
  }

  componentDidMount() {
    console.log("component did mount");
  }
  componentDidUpdate() {
    console.log("component did update");
  }

  onClick = () => {
    this.setState({ count: this.state.count + 1 });
  };
  render() {
    console.log("render");
    return (
      <div>
        Hello Test
        <button onClick={this.onClick}>
      		{this.state.count}
		</button>
      </div>
    );
  }
}


//--for first time
//Constructor
//render
//component did mount
//--for any update
//render
//component did update

Example 3: lifecycle method react

INITIALIZATION= setup props and state 
MOUNTING= constructor->componentWillMount->render->componentDidMount//Birth
UPDATE= shouldComponentUpdate->componentWillUpdate->render
  		->componentDidUpdate //Growth
UNMOUNTING= componentWillUnmount //Death

Example 4: lifecycles if reactjs

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {  }
  componentWillUnmount() {  }
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

Example 5: react lifecycle

constructor(props) {
  super(props);
  // Don't call this.setState() here!
  this.state = { counter: 0 };
  this.handleClick = this.handleClick.bind(this);
}

Example 6: Component life cycle

class LifeCycle extends React.Component {
      constructor(props)
      {
        super(props);
         this.state = {
           date : new Date(),
           clickedStatus: false,
           list:[]
         };
      }
      componentWillMount() {
          console.log('Component will mount!')
       }
      componentDidMount() {
          console.log('Component did mount!')
          this.getList();
       }
      getList=()=>{
       /*** method to make api call***
       fetch('https://api.mydomain.com')
          .then(response => response.json())
          .then(data => this.setState({ list:data }));
      }
       shouldComponentUpdate(nextProps, nextState){
         return this.state.list!==nextState.list
        }
       componentWillUpdate(nextProps, nextState) {
          console.log('Component will update!');
       }
       componentDidUpdate(prevProps, prevState) {
          console.log('Component did update!')
       }
      render() {
          return (
             <div>
                <h3>Hello Mounting Lifecycle Methods!</h3>
             </div>
          );
       }
}