React Component Lifecycle

Dr. Greg Bernstein

Updated April 20th, 2021

Component Lifecycle

Component Lifecycle Diagram

From react-lifecycle

Life Cycle Diagram

Life Cycle Methods 1

class MyComponent extends React.Component {
    constructor(props) {/*stuff*/ }
    render() {/* stuff */ }

    componentDidMount() {
        // Called right after the component is created
        // in the DOM
    }

    componentWillUnmount() {
        // Called right before the component is removed
        // from the DOM
    }
    // Other life cycle methods are available
}

Life Cycle Methods 2

  • Are part of the React framework
  • Are in your class components via Inheritance
  • Needed in specific situations, but not in many others

Life Cycle Methods Example

Example: a Clock component

  • Let’s create a self contained clock component

  • Keeps the “latest time” as internal state

  • Updates itself every second to update the state

Adding internal state

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

    render() {
        return <div>
            <h2>The date and time is:</h2>
            <h2>{this.state.date}</h2>
        </div>
    }
}

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

React.Component constructor

From constructor

  • Initialize local state by assigning an object to this.state
  • Do not call setState() in the constructor! This is the only exception to the rule that all state changes are made by calling setState()

Does it work?

  • It renders, but it doesn’t update.

  • We need to start and stop a timer that updates the state

  • Where should we do this?

Updating Logic

Be careful with this!

    tick() { // function to call on timer ticks, see use of setState!
        this.setState({date: new Date().toLocaleString()});
    }

    componentDidMount() {// Note use of bind below:
        this.timerId = window.setInterval(this.tick.bind(this), 1000);
    }

    componentWillUnmount() {
        window.clearInterval(this.timerId);
    }

Complete Clock component

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

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

    componentDidMount() {
        this.timerId = window.setInterval(this.tick.bind(this), 1000);
    }

    componentWillUnmount() {
        window.clearInterval(this.timerId);
    }

    render() {
        return <div>
            <h2>The date and time is:</h2>
            <h2>{this.state.date}</h2>
        </div>
    }
}

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