DocumentationRulesweb-api/no-leaked-interval

no-leaked-interval

Rule category

Correctness.

What it does

Enforce that every setInterval in a component or custom hook has a corresponding clearInterval.

Why is this bad?

Scheduling a interval within the setup function of useEffect without canceling it in the cleanup function can lead to unwanted setInterval callback executions and may also result in using stale values captured by previous render’s effects after each subsequent re-render.

Examples

Failing

import React, { useEffect, useState } from 'react';
 
function Example() {
  const [count, setCount] = useState(0);
 
  useEffect(() => {
    const intervalId = setInterval(() => console.log(count), 1000);
    //                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    //                 - A 'setInterval' created in 'useEffect' must be cleared in the cleanup function.
  }, []);
 
  return null;
}

Passing

import React, { useEffect, useState } from 'react';
 
function Example() {
  const [count, setCount] = useState(0);
 
  useEffect(() => {
    const intervalId = setInterval(() => console.log(count), 1000);
    return () => clearInterval(intervalId);
  }, []);
 
  return null;
}

Further Reading