Movatterモバイル変換


[0]ホーム

URL:


Global event handlers should be properly removed during React component lifecycle

  • REACT_MISSING_CLEANUP_IN_LIFECYCLE
  • Error
  • Medium
  • react

This rule applies when global event handlers are added, but not removed properly during the lifecycle of a React class component.

In general, global handlers added atcomponentDidMount() should be explicitly removed atcomponentWillUnmount() 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 thewindow object
  2. Event listeners on thedocument object
  3. setInterval() handlers

Noncompliant Code ExampleCompliant Code Example
1import React from 'react';1import React from 'react';
22
3export default class Hello extends React.Component {3export default class Hello extends React.Component {
4 update = () => {4 update = () => {
5 this.forceUpdate();5 this.forceUpdate();
6 }6 }
7 componentDidMount() {7 componentDidMount() {
8 window.addEventListener('hashchange', this.update, false); // REACT_MISSING_CLEANUP_IN_LIFECYCLE alarm8 window.addEventListener('hashchange', this.update, false);
9 }9 }
10 componentWillUnmount() {10 componentWillUnmount() {
11 window.removeEventListener('hashChange', this.update, false); // 'C' is upper-case11 window.removeEventListener('hashchange', this.update, false);
12 }12 }
13 render() {13 render() {
14 return <div>Hello</div>;14 return <div>Hello</div>;
15 }15 }
16}16}

Noncompliant Code Example

View with compliant examples side by side
import React from 'react';export default class Hello extends React.Component {  update = () => {    this.forceUpdate();  }  componentDidMount() {    window.addEventListener('hashchange', this.update, false); // REACT_MISSING_CLEANUP_IN_LIFECYCLE alarm  }  componentWillUnmount() {    window.removeEventListener('hashChange', this.update, false); // 'C' is upper-case  }  render() {    return <div>Hello</div>;  }}

Compliant Code Example

View with noncompliant examples side by side
import React from 'react';export default class Hello extends React.Component {  update = () => {    this.forceUpdate();  }  componentDidMount() {    window.addEventListener('hashchange', this.update, false);  }  componentWillUnmount() {    window.removeEventListener('hashchange', this.update, false);  }  render() {    return <div>Hello</div>;  }}

Version

This rule was introduced in DeepScan 1.27.0.

Was this documentation helpful?

Last updated on April 29, 2025

[8]ページ先頭

©2009-2025 Movatter.jp