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-intervalFull Name in @eslint-react/eslint-plugin
@eslint-react/web-api-no-leaked-intervalPresets
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.
Examples
Setting interval without cleanup in useEffect
import React, { useEffect, useState } from "react";
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
// Problem: A 'setInterval' created in 'useEffect' must be cleared in the cleanup function.
const intervalId = setInterval(() => console.log(count), 1000);
}, []);
return null;
}Clearing interval in useEffect cleanup
import React, { useEffect, useState } from "react";
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
// Recommended: Store the interval ID
const intervalId = setInterval(() => console.log(count), 1000);
// Recommended: Clear the interval in the cleanup function
return () => clearInterval(intervalId);
}, []);
return null;
}Versions
Resources
Further Reading
See Also
react-web-api/no-leaked-event-listener
Enforces that everyaddEventListenerin a component or custom hook has a correspondingremoveEventListener.react-web-api/no-leaked-fetch
Enforces that everyfetchin a component or custom hook has a correspondingAbortControllerabort in the cleanup function.react-web-api/no-leaked-resize-observer
Enforces that everyResizeObservercreated in a component or custom hook has a correspondingResizeObserver.disconnect().react-web-api/no-leaked-timeout
Enforces that everysetTimeoutin a component or custom hook has a correspondingclearTimeout.