Photo by Icons8 team on Unsplash
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
😅 Reproducing the Issue
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! 😱
🔧 How to Fix the Issue
You need to save the interval ID when you call the setInterval
.
Reference: WindowOrWorkerGlobalScope.setInterval()
To cancel setInterval
, you need to call clearInterval
, which require the interval ID returned when you called setInterval
.
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 componentWillUmount
.
The post Canceling interval in React appeared first on Sung's Technical Blog.
Top comments (11)
Neat tip! Asynchronous code can't be tricky to deal with when unmounting a component. For example, if you call a promise in a component and then immediately unmount the component, the promise call execution will continue :S.
Thanks Robert for the cancelable promise issue.
Wow, I just looked up how to cancel promises and there are so many results and tc39 proposal for cancelable promise has been withdrawn.
How would you cancel the promise call execution?
That's a good question, lol. I would have to google it. I've run into the issue in the past, but can't remember how I went about resolving the problem :/
If I run into the situation and have to deal with it, I will share.
Thanks for the heads up, Robert 👊
Great tip, slick solution!
Thanks Joe.
componentWillUnmount is like
Dispose
(in C#), which is where you clean up stuff.But left it out to keep it purely JavaScript
So basic and yet I had completely forgotten about this! Thank you so much!!
You're welcome 😎 & thanks for the feedback there cg-h4voK 🙏
Thank you! This was really helpful.
Hey, i did the same way you did here, but still my app using Reactnative showing error about - cant perform react state update on unmounted component, memory leak error
I am not familiar with RN and do you have a code snippet or runnable sample (Expo?)
The way it's handled is different w/ introduction of hooks too.