Canceling setInterval in React

react, javascript


title: Canceling setInterval in React date: "2018-09-15" published_at: "2018-09-15T19:35:58.000Z" tags: "react, javascript" author: Sung M. Kim banner: ./images/featured-image.jpg

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.

class Greeting extends Component {
hello = id => console.log(`hello world! - ${id}`);
componentDidMount() {
const id = shortid.generate();
setInterval(e => this.hello(id), 1000);
componentWillUnmount() {
console.log("Greeting unmounted...");
render() {
return (
<Link to="/main">Go to Main Page</Link>
view raw Greeting.js hosted with ❤ by GitHub


Edit setInterval NOT cleared before unmounting

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! 😱

Error Reproduced

🔧 How to Fix the Issue

You need to save the interval ID when you call the setInterval.

Reference: WindowOrWorkerGlobalScope.setInterval()

class Greeting extends Component {
intervalID = 0;
componentDidMount() {
this.intervalID = setInterval(this.hello, 1000);

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).

componentWillUnmount() {

You can see below that the interval doesn't run any more after canceled within componentWillUmount.

The interval canceled


Edit setInterval cleared before unmounting

Try it for yourself