Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

reactjs - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...