React.PureComponent
prop should not be specified with a newly created object
This rule applies when a property value of props object inReact.PureComponent
always has a newly created object.
TheshouldComponentUpdate()
method ofReact.PureComponent
checks the change with strict equality on properties of props and state objects.
So a new object is detected as a change although it is seemingly equal.
Those new objects could be unintended and always leads to the unnecessary difference computation even when there is no real change.
One of the most common cases of this problem is creating a different callback each time for a prop by an arrow function or abind
call.
We generally recommend using the property initializer syntax or binding in the constructor, to avoid this sort of performance problem.
Noncompliant Code Example | Compliant Code Example | ||
---|---|---|---|
... | ... | ||
4 | constructor(props) { | 4 | constructor(props) { |
5 | super(props); | 5 | super(props); |
6 | this.handleClick = () => this.props.onClick(); | 6 | this.handleClick = () => this.props.onClick(); |
7 | } | 7 | } |
8 | render() { | 8 | render() { |
9 | return <button onClick={this.handleClick}>BUTTON</button>; | 9 | return <button onClick={this.handleClick}>BUTTON</button>; |
10 | } | 10 | } |
11 | } | 11 | } |
12 | 12 | ||
13 | export class App extends React.Component { | 13 | export class App extends React.Component { |
14 | constructor(props) { | ||
15 | super(props); | ||
16 | this.handleClick = () => { | ||
17 | this.setState({clicked: true}); | ||
18 | }; | ||
19 | } | ||
14 | render() { | 20 | render() { |
15 | return <Button onClick={() => { this.setState({clicked: true}); }} />; // REACT_INEFFICIENT_PURE_COMPONENT_PROP alarm because a new object is passed to 'onClick' handler. | 21 | return <Button onClick={this.handleClick} />; |
16 | } | 22 | } |
17 | } | 23 | } |
import React from 'react';class Button extends React.PureComponent { constructor(props) { super(props); this.handleClick = () => this.props.onClick(); } render() { return <button onClick={this.handleClick}>BUTTON</button>; }}export class App extends React.Component { render() { return <Button onClick={() => { this.setState({clicked: true}); }} />; // REACT_INEFFICIENT_PURE_COMPONENT_PROP alarm because a new object is passed to 'onClick' handler. }}
import React from 'react';class Button extends React.PureComponent { constructor(props) { super(props); this.handleClick = () => this.props.onClick(); } render() { return <button onClick={this.handleClick}>BUTTON</button>; }}export class App extends React.Component { constructor(props) { super(props); this.handleClick = () => { this.setState({clicked: true}); }; } render() { return <Button onClick={this.handleClick} />; }}
This rule was introduced in DeepScan 1.8.0-beta.