Sometimes you need to run a command in an interval using window.setInterval.
But if you don’t stop the interval when the component using the
setInterval is not stopped, it will continuously run using unnecessary resources.
I will talk about how to handle
setInterval in React
Let’s create a very “contrived” example that prints “hello world” every second in console.
Follow along on CodeSandBox
When you navigate away from the component (to simulate unmounting), the interval still runs.
Even worse, when you navigate back to
Greeting component, another interval process starts! 😱
You need to save the interval ID when you call the
setInterval, you need to call
clearInterval, which require the interval ID returned when you called
The best place to do is right before the component unmounts (componentWillUnmount).
You can see below that the interval doesn’t run any more after canceled within