Ghosty
0
Q:

lifecycle methods react

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
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>
    );
  }
}
2
class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));
 
 
 
 
 
1
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
6
componentDidMount()
2
shouldComponentUpdate(nextProps, nextState) {
  return true;
}
0
componentDidUpdate(prevProps, prevState, snapshot)
2

New to Communities?

Join the community