React Three
Component Lifecycle & React Review
What is the Component Lifecycle?
The Component Lifecycle refers to the 'life' and 'death' of a React component.
There are three main phases of the lifecycle:
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(prevProps, prevState){
//componentDidUpdate optionally takes in a reference to the
//previous props and state objects to make comparisons if needed
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 invoked after render
React 3
By Devmountain
React 3
Component Lifecycle and Group Review
- 1,206