logoESLint React
Rules

no-leaked-interval

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

Full Name in eslint-plugin-react-web-api

react-web-api/no-leaked-interval

Full Name in @eslint-react/eslint-plugin

@eslint-react/web-api/no-leaked-interval

Presets

web-api recommended recommended-typescript recommended-type-checked strict strict-typescript strict-type-checked

Rule Details

Scheduling an 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 renders’ effects after each subsequent re-render.

Common Violations

Invalid

import React, { useEffect, useState } from "react";

function MyComponent() {
  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;
}

Valid

import React, { useEffect, useState } from "react";

function MyComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => console.log(count), 1000);
    return () => clearInterval(intervalId);
  }, []);

  return null;
}

Resources

Further Reading


See Also

On this page