简体   繁体   中英

Is it really necessary to clear the timers before unmounting the component?

Usually timers will be cleared before unmounting the component from DOM. But what would be the side effects if we forgot to clear the timers?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM