1

I was just going through the code of react-slick and came across the following peice of code:-

this.callbackTimers.push(
     setTimeout(() => this.setState({ animating }), 10)
);

In the componentWillUnmount the callbackTimers are cleared like so :-

componentWillUnmount = () => {
    if (this.callbackTimers.length) {
      this.callbackTimers.forEach(timer => clearTimeout(timer));
      this.callbackTimers = [];
    }
};

Is the sole purpose of using the array to free memory or is there something that i have missed here ?

Why not just call the setTimeout directly:

setTimeout(() => this.setState({ animating }), 10)

instead of using an array ? i do see callbackTimers being used elsewhere too , but i don't know why exactly this array is needed apart from freeing memory, Is there any other purpose to this array ?

The line in question can be found HERE.

Alexander Solonik
  • 9,838
  • 18
  • 76
  • 174
  • 2
    Any timers that aren't expired yet are cleared so they don't trigger after the component has unmounted. Keeping references to them in an array is just the simplest way to do that. –  Sep 23 '20 at 12:03
  • @Alexander Solonik, setTimeout returns timer id which we can use for clearTimeout for preventing memory leak or as Chris mention for preventing the code to run after unmounting of the component. – Pulkit Aggarwal Sep 23 '20 at 12:05
  • Have you ever run into calling `setState` on an unmounted component? – Felix Kling Sep 23 '20 at 12:10
  • @FelixKling not really no , i beleive not having the array and clearing it could cause that ? – Alexander Solonik Sep 23 '20 at 12:15
  • @PulkitAggarwal makes sense thanks .. – Alexander Solonik Sep 23 '20 at 12:15
  • 1
    @AlexanderSolonik with reference to what Felix mentioned, consider a case where a component makes a HTTP request but for some reason component unmounts before that request is completed, in this case, you will get [this warning](https://stackoverflow.com/questions/40295315/warning-about-calling-setstate-on-an-unmounted-component) – Yousaf Sep 23 '20 at 12:19
  • @Yousaf makes perfect sense, thanks. – Alexander Solonik Sep 23 '20 at 12:21

1 Answers1

2

clearTimeout() function is only necessary to cancel any pending timers. Otherwise, you don't really need to call clearTimeout() function to clear the memory.

In the code in your question, timers are cleared in the componentWillUnmount lifecycle method to cancel any pending timers when component is about to unmount. This will prevent any code in the callback function of any pending timer, from executing once the component has unmounted.

Yousaf
  • 27,861
  • 6
  • 44
  • 69