Skip to content

Instantly share code, notes, and snippets.

@ross-u
Last active February 26, 2020 17:06
Show Gist options
  • Save ross-u/38fa3558155234faf453e6730755759a to your computer and use it in GitHub Desktop.
Save ross-u/38fa3558155234faf453e6730755759a to your computer and use it in GitHub Desktop.
React Lifecycle methods - III Unmounting - componentWillUnmount()

React | Lifecycle methods


III - Unmounting


componentWillUnmount() is invoked immediately before a component is unmounted and destroyed (removed from the DOM).

Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, like for example stopping setInterval() timers before the component gets destroyed to prevent memory leaking .

You should not call setState() in the componentWillUnmount() because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.

import React from 'react';
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
year: 2020,
timerId: null, // <-- CREATE NEW PROPERTY
timer: 0, // <-- CREATE NEW PROPERTY
};
console.log('IN CONSTRUCTOR');
}
// CREATE A METHOD TO UPDATE THE TIMER IN THE `state`
updateTimer = () => { // <-- CREATE A NEW METHOD
this.setState({ timer: this.state.timer + 1 });
};
// UPDATE THE CODE IN THE componentDidMount()
componentDidMount() {
console.log('IN "COMPONENT DID MOUNT"');
const timerId = setInterval(this.updateTimer, 1000); // <-- CREATE AN INTERVAL
this.setState({ year: this.props.currentYear, timerId }); // <-- SET timerId
}
componentDidUpdate(prevProps, prevState) {
console.log('IN "COMPONENT DID UPDATE"');
if (prevProps.currentTime !== this.props.currentTime) {
console.log(' RECEIVED NEW PROPS ! ! !');
}
}
// ADD THE LIFECYLCLE METHOD `componentWillUnmount()`
// TO CLEAR THE TIMEOUT BEFORE THE COMPONENT IS DESTROYED
componentWillUnmount() { // <-- ADD
console.log('X IN "COMPONENT WILL UNMOUNT" X');
clearTimeout(this.state.timerID); // <-- ADD
}
render() {
console.log('IN RENDER');
return (
<div>
<h1>Clock</h1>
<h2>Year</h2>
<p>{this.state.year}</p>
<h2>Current Time</h2>
<p>
{
this.props.currentTime
? this.props.currentTime
: "LOADING"
}
</p>
<h2>Timer: {this.state.timer} </h2> {/* <-- ADD */}
</div>
);
}
}
export default Clock;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment