OverriddenshouldComponentUpdate()
should not always return a truthy value
This rule applies when an overriddenshouldComponentUpdate()
method always returns a truthy value.
SinceshouldComponentUpdate()
defaults totrue
, it is useless if the overriddenshouldComponentUpdate()
method always returns a truthy value.
In this case,shouldComponentUpdate()
method's logic is probably wrong by a developer's mistake or misunderstanding of the method.
Noncompliant Code Example | Compliant Code Example | ||
---|---|---|---|
1 | import React from 'react'; | 1 | import React from 'react'; |
2 | 2 | ||
3 | export class Hello extends React.Component { | 3 | export class Hello extends React.Component { |
4 | constructor(props) { | 4 | constructor(props) { |
5 | super(props); | 5 | super(props); |
6 | this.state = { greetName: 'Hi' }; | 6 | this.state = { greetName: 'Hi' }; |
7 | this.handleClick = this.handleClick.bind(this); | 7 | this.handleClick = this.handleClick.bind(this); |
8 | } | 8 | } |
9 | handleClick() { | 9 | handleClick() { |
10 | this.setState({ greetName: 'Bye' }); | 10 | this.setState({ greetName: 'Bye' }); |
11 | } | 11 | } |
12 | shouldComponentUpdate(nextProps, nextState) { // REACT_USELESS_SHOULD_COMPONENT_UPDATE alarm because this always returns true. | 12 | shouldComponentUpdate(nextProps, nextState) { |
13 | if (nextState.greetName !== this.state.greetName) { | 13 | if (nextState.greetName !== this.state.greetName) { |
14 | return true; | 14 | return true; |
15 | } | 15 | } |
16 | return true; | 16 | return false; |
17 | } | 17 | } |
18 | render() { | 18 | render() { |
19 | return <div onClick={this.handleClick}>{this.state.greetName}</div>; | 19 | return <div onClick={this.handleClick}>{this.state.greetName}</div>; |
20 | } | 20 | } |
21 | } | 21 | } |
import React from 'react';export class Hello extends React.Component { constructor(props) { super(props); this.state = { greetName: 'Hi' }; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState({ greetName: 'Bye' }); } shouldComponentUpdate(nextProps, nextState) { // REACT_USELESS_SHOULD_COMPONENT_UPDATE alarm because this always returns true. if (nextState.greetName !== this.state.greetName) { return true; } return true; } render() { return <div onClick={this.handleClick}>{this.state.greetName}</div>; }}
import React from 'react';export class Hello extends React.Component { constructor(props) { super(props); this.state = { greetName: 'Hi' }; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState({ greetName: 'Bye' }); } shouldComponentUpdate(nextProps, nextState) { if (nextState.greetName !== this.state.greetName) { return true; } return false; } render() { return <div onClick={this.handleClick}>{this.state.greetName}</div>; }}
This rule was introduced in DeepScan 1.4.0-beta.