no-leaked-timeout
Full Name in eslint-plugin-react-web-api
react-web-api/no-leaked-timeout
Full Name in @eslint-react/eslint-plugin
@eslint-react/web-api/no-leaked-timeout
Features
🔍
Presets
web-api
recommended
recommended-typescript
recommended-type-checked
What it does
Enforces that every setTimeout
in a component or custom hook has a corresponding clearTimeout
.
Why is this bad?
Scheduling a timeout within the setup function of useEffect
without canceling it in the cleanup function can lead to unwanted setTimeout
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 timeoutId = setTimeout(() => console.log(count), 1000);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// - A 'setTimeout' 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 timeoutId = setTimeout(() => console.log(count), 1000);
return () => clearTimeout(timeoutId);
}, []);
return null;
}