React Three

Component Lifecycle

What is the Component Lifecycle?

The Component Lifecycle refers to the 'life' and 'death' of the component on the viewport. There are four main phases of the lifecycle:

Initialization

Mounting

Updating

Unmounting

Lifecycle Methods

In React, we can take advantage of a Components Lifecycle with built-in lifecycle methods. These methods allow us to perform functionality at different parts of the component lifecycle. Some of the more common lifecycle methods are:

componentDidMount

componentDidUpdate

render

When Lifecycle Methods Fire

componentDidMount

componentDidMount will be invoked after the component initially renders on the screen. This is a great method if you need certain functionality to fire as soon as the component is in the viewport.

import React, {Component} from 'react';

class GreetingComponent extends Component {
  constructor(){
    super();
    this.state = {
      username: 'Matt'
    }
  }
  
  componentDidMount(){
    alert(`Hello, ${this.state.username}`)
  }
  
  render(){
    <div>Display Here</div>
  }
}

export default GreetingComponent;

Render is invoked to mount the display

Invoked after render

componentDidUpdate

componentDidUpdate won't fire after the initial render, but on each render after. Remember, render will be re-invoked after any change in state or props.

componentDidUpdate(){
  alert(`New username is ${this.state.username}`)
}
  
changeUsername = () => {
 this.setState({
   username: 'Bob Ross'
 })
}
  
render(){
  <div>Display Here</div>
}

Render is invoked after state changes

Function changes state

componentDidUpdate is then invoked after render

React Three

By Matthew Bodily

React Three

  • 216