React.PureComponent prop should not be specified with a newly created object

  • REACT_INEFFICIENT_PURE_COMPONENT_PROP
  • Code Quality
  • Low
  • react

This rule applies when a property value of props object in React.PureComponent always has a newly created object.

The shouldComponentUpdate() method of React.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 a bind call.
We generally recommend using the property initializer syntax or binding in the constructor, to avoid this sort of performance problem.

Noncompliant Code Example

import React from 'react';

class App extends React.Component {
    render() {
        return <Button onClick={() => { this.setState({clicked: true}); }}/>;  // REACT_PURE_COMPONENT_NEW_OBJECT_PROP alarm because a new object is passed to 'onClick' handler.
    }
}

class Button extends React.PureComponent {
    constructor(props) {
        super(props);
        this.handleClick = () => this.props.onClick();
    }
    render() {
        return <button onClick={this.handleClick}>BUTTON</button>;
    }
}

Compliant Code Example

import React from 'react';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.handleClick = () => {
            this.setState({clicked: true});
        };
    }
    render() {
        return <Button onClick={this.handleClick}/>;
    }
}

class Button extends React.PureComponent {
    constructor(props) {
        super(props);
        this.handleClick = () => this.props.onClick();
    }
    render() {
        return <button onClick={this.handleClick}>BUTTON</button>;
    }
}

Version

This rule was introduced in DeepScan 1.8.0-beta.

See