Q:

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
5
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.

Mounting – Birth of your component
Update – Growth of your component
Unmount – Death of your component
8
INITIALIZATION= setup props and state 
MOUNTING= constructor->componentWillMount->render->componentDidMount//Birth
UPDATE= shouldComponentUpdate->componentWillUpdate->render
  		->componentDidUpdate //Growth
UNMOUNTING= componentWillUnmount //Death
5
constructor(props) {
  super(props);
  // Don't call this.setState() here!
  this.state = { counter: 0 };
  this.handleClick = this.handleClick.bind(this);
}
1

New to Communities?

Join the community