Suppose you call a timer
in some function and when you navigate to another component and your current component has unmounted
, if you do not clear the timer, your function will continue to be executed.
Hence in the componentWillUnmount
function you need to clear the timer which can be identified by the numeric value returned by setInterval
AS mentioned in the React DOCS:
componentWillUnmount()
is invoked immediately before a component is
unmounted and destroyed. Perform any necessary cleanup in this method,
such as invalidating timers, canceling network requests, or cleaning
up any DOM elements that were created in componentDidMount
Example:
componentDidMount() {
this.timerID = setInterval(
() => this.somefunc(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
SideEffect:
Consider a case when in the timer you are making the API call from which you are getting data that you display in your component. Now if you navigate away from the component you wouldn't normally want to be calling the API again and again even though you don't need the result. This will cause and Unnecessary load on the Server.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…