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,

  1. It can be executed unnecessarily.
  2. Data reachable from it cannot be garbage-collected and a memory leak would occur.

Currently, this rule detects alarms on the following global handlers:

  1. Event listeners on the window object
  2. Event listeners on the document object
  3. setInterval() handlers

This rule also applies to the analogous useLayoutEffect Hook.

Noncompliant Code Example

View with compliant examples side by side
import 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 side
import 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