Global event handlers should be properly removed during React component lifecycle
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,
Currently, this rule detects alarms on the following global handlers:
window
objectdocument
objectsetInterval()
handlersNoncompliant Code Example | Compliant Code Example | ||
---|---|---|---|
1 | import React from 'react'; | 1 | import React from 'react'; |
2 | 2 | ||
3 | export default class Hello extends React.Component { | 3 | export 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 alarm | 8 | window.addEventListener('hashchange', this.update, false); |
9 | } | 9 | } |
10 | componentWillUnmount() { | 10 | componentWillUnmount() { |
11 | window.removeEventListener('hashChange', this.update, false); // 'C' is upper-case | 11 | 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 | } |
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>; }}
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>; }}
This rule was introduced in DeepScan 1.27.0.