Global event handlers added at React Effect Hooks should be properly removed at the cleanup function
- REACT_MISSING_CLEANUP_IN_EFFECT_HOOK
- Error
- Medium
- react
This rule applies when global event handlers are added during the execution of useEffect()
, but not removed properly at the effect cleanup function.
In general, global handlers should be explicitly removed at the cleanup function because they persist beyond the React component lifecycle.
If the handler is not removed,
- It can be executed unnecessarily.
- Data reachable from it cannot be garbage-collected and a memory leak would occur.
Currently, this rule detects alarms on the following global handlers:
- Event listeners on the
window
object - Event listeners on the
document
object setInterval()
handlers
This rule also applies to the analogous useLayoutEffect
Hook.
Noncompliant Code Example
View with compliant examples side by sideimport React, { useEffect } from 'react';
function foo() {
alert("clicked!");
}
export function Hello(props) {
useEffect(() => {
document.addEventListener("click", foo); // REACT_MISSING_CLEANUP_IN_EFFECT_HOOK alarm
});
return <div>Hello, {props.name}</div>;
}
Compliant Code Example
View with noncompliant examples side by sideimport React, { useEffect } from 'react';
function foo() {
alert("clicked!");
}
export function Hello(props) {
useEffect(() => {
document.addEventListener("click", foo);
return () => {
document.removeEventListener("click", foo);
};
});
return <div>Hello, {props.name}</div>;
}
Version
This rule was introduced in DeepScan 1.27.0.
See
React Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.