
After this lesson, you will be able to:
The life cycle comprises three main stages:
When the component is being created (known as mounting).
When the component is being updated.
When the component is being removed from the DOM (known as unmounting).
These methods are called at specific points in the rendering process. You can use them to perform actions based on what’s happening on the DOM.
componentDidMount(), for example, is called immediately after a component is rendered to the DOM.componentWillUnmount() is called immediately before a component is removed from the DOM.constructor()static getDerivedStateFromProps()render()componentDidMount()static getDerivedStateFromProps()shouldComponentUpdate()render()getSnapshotBeforeUpdate()componentDidUpdate()componentWillUnmount()
constructor() Methodconstructor() Methodconstructor() MethodAnother common use of the constructor() method is to bind class methods.
For example, we could set:
In JavaScript classes, methods aren’t bound by default. So, if you pass a component’s method to a child component without binding it, its context will be bound to the child and not the parent, causing it to behave in a way other than how you intended.
Here’s an example:
class FruitTable extends Component {
state = {
fruits: props.fruits
}
}
addFruit = (fruit) => {
this.setState(prevState => ({
fruits: prevState.fruits.concat(fruit)
}))
}
}static getDerivedStateFromProps() and getSnapshotBeforeUpdate() MethodsgetDerivedStateFromProps() is invoked right before calling the render() method. It should return an object to update the state or null to update nothing.
getSnapshotBeforeUpdate() is invoked right before the most recently rendered output is committed (e.g., to the DOM).
Note:: These methods exists for rare use cases in which the state depends on changes in props over time (getDerivedStateFromProps()) or if you need to handle something such as scroll position before an update (getSnapshotBeforeUpdate()). It’s a best practice to explore other lifecycle methods before using these.
componentDidMount() and componentWillUnmount() MethodsThe componentDidMount method is called once, immediately after your component is rendered to the DOM. If you want to make an AJAX request when your component first renders, do so here (not in the constructor or in componentWillMount()).
In the following example, we fetch data from the server, then set the state of the component using the response:
componentDidMount() {
fetch(`http://api.com/${this.props.id}`)
.then(response => response.json())
.then(data => this.setState(prevState => ({ data })));
}componentDidMount() and componentWillUnmount() Methodsclass FruitTable extends Component {
componentDidMount() {
document.addEventListener('dragover', this.handleDragStart)
}
componentWillUnmount() {
document.removeEventListener('dragover', this.handleDragStart)
}
handleDragStart = (e) => {
e.preventDefault()
this.setState({ dragging: true});
}
}render() MethodThis is the one method that every React class component must have. It is called in two parts of the component life cycle: At the beginning, when the component is being initiated/mounted, and when the component is being updated.
render(), you return JSX using this.props and this.state.The following component renders a single prop and a single state key: A car model and a speed. Once this component is mounted, its speed state will increase by 1 every second. You can try it out yourself in this CodePen.
class Car extends Component {
constructor(props) {
super(props)
// Sets initial state to either the speed prop, or 0 if the speed prop
// is not passed to the component.
this.state = {
speed: this.props.speed || 0
}
// Binds this.incrementSpeed to class.
// This way, when it's used as a callback for setTimeout,
// `this` refers to the Car class.
this.incrementSpeed = this.incrementSpeed.bind(this);
}
componentDidMount() {
// Calls this.incrementSpeed after one second.
window.setTimeout(this.incrementSpeed, 1000);
}
incrementSpeed() {
// Sets the speed state to one unit higher than it was previously.
this.setState(prevState => ({ speed: prevState.speed + 1 }));
// Recursive method.
// Increases speed by 1 again after one second.
window.setTimeout(this.incrementSpeed, 1000);
}
render() {
return (
<div>
This {this.props.model} is going {this.state.speed} miles per hour!
</div>
)
}
}constructor()The initial state is set to either the speed prop, or 0 if the speed prop is not passed to the component.
We bind this.incrementSpeed to the class, so that when it’s used as a callback for setTimeout, this refers to the Car class.
componentDidMount()Use window.setTimeout to call this.incrementSpeed after one second (1,000 ms).
incrementSpeed()this.setState(prevState => ({ speed: prevState.speed + 1 })): The speed state is set to one higher than it was previously — we add 1.
window.setTimeout(this.incrementSpeed, 1000): The incrementSpeed method is recursive — it invokes itself as the timeout callback. After one second, window.setTimeout will call this.incrementSpeed again. The speed will increase by 1, and a new timer will be set to do it again.
class Car extends Component {
// Sets initial state to either the speed prop, or 0 if the speed prop
// is not passed to the component.
state = {
speed: props.speed || 0
}
componentDidMount() {
// Calls this.incrementSpeed after one second.
window.setTimeout(this.incrementSpeed, 1000);
}
// Binds this.incrementSpeed to class using the arrow syntax.
// This way, when it's used as a callback for setTimeout,
// `this` refers to the Car class.
incrementSpeed = () => {
// Sets the speed state to one unit higher than it was previously.
this.setState(prevState => ({ speed: prevState.speed + 1 }));
// Recursive method.
// Increases speed by 1 again after one second.
window.setTimeout(this.incrementSpeed, 1000);
}
render() {
return (
<div>
This {this.props.model} is going {this.state.speed} miles per hour!
</div>
)
}
}shouldComponentUpdate() MethodshouldComponentUpdate() lets React know if a component’s output is not affected by the current change in state or props. The default returns true and re-renders on every state change.
If shouldComponentUpdate() returns false, then render() and componentDidUpdate() will not be invoked.
componentDidUpdate() MethodcomponentDidUpdate(prevProps, prevState, snapshot)
// Example expanding our previous render() example:
componentDidUpdate(prevProps) {
// Don't forget to compare props!
if (this.props.model !== prevProps.model) {
this.fetchData(this.props.model);
}
}React class components have life-cycle methods that are invoked at certain stages of their “lives” on the DOM. Some of the life-cycle methods you’ll use frequently include:
constructor(): Initializes state, binds methods.componentDidMount(): Makes AJAX requests, gets DOM refs, binds event listeners, sets state if necessary.componentWillUnmount(): Unbinds event listeners, performs other clean-up.componentDidUpdate(): Updates state based on changes in components.render(): Returns markup/UI.