A component extending React.PureComponent
should not override shouldComponentUpdate()
lifecycle method
- REACT_REDUNDANT_SHOULD_COMPONENT_UPDATE
- Code Quality
- Low
- react
This rule applies when a component extending React.PureComponent
overrides shouldComponentUpdate()
lifecycle method.
React.PureComponent
implements shouldComponentUpdate()
method to determine re-rendering with a shallow prop and state comparison for rendering performance optimization.
Although overridden shouldComponentUpdate()
method will work as intended, React.PureComponent
plays no role in such a case and React outputs a warning message. Therefore, if you need your own shouldComponentUpdate()
, it is recommended to use React.Component
instead.
Noncompliant Code Example
View with compliant examples side by sideimport React from 'react';
export class Hello extends React.PureComponent {
constructor(props) {
super(props);
this.state = { greetName: "Hi" };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({ greetName: "Bye" });
}
shouldComponentUpdate(nextProps, nextState) { // REACT_REDUNDANT_SHOULD_COMPONENT_UPDATE alarm because 'Hello' component extends 'React.PureComponent' but overrides 'shouldComponentUpdate()'.
if (nextState.greetName !== this.state.greetName) {
return true;
}
return false;
}
render() {
return (<div onClick={this.handleClick}>{this.state.greetName}</div>);
}
}
Compliant Code Example
View with noncompliant examples side by sideimport 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>);
}
}
Version
This rule was introduced in DeepScan 1.4.0-beta.
See
React Warning: Hello has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.