Components: Lifecycle

Lifecycle — Special methods on the component class to run some code when a component mounts and unmounts.

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

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

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

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

ComponentDidMount()

Runs after the component output has been rendered to the DOM.

ComponentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

ComponentWillUnmount()

componentWillUnmount() {
    clearInterval(this.timerID);
  }

Render()

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

Components: Lifecycle — Structure map

Clickable & Draggable!

Components: Lifecycle — Related pages: