buildo-react-pure

1.0.1 • Public • Published

react-pure

@pure is a light decorator that adds shouldComponentUpdate to pure react components to improve performance.

Install

npm i --save buildo-react-pure

Usage

@pure decorator can only be applied to React.Component(s) classes.

@pure
export default class MyComponent extends React.Component {
 
  render() {
    return <div />
  }
 
}

Under the hood

@pure adds the logic to the method shouldComponentUpdate to perform a shallow compare between current and previous props/state. If nor the props nor the state refs have changed, shouldComponentUpdate will return false and React will automatically use the result cached from previous render: you avoid a useless re-render!

@pure
export default class MyComponent extends React.Component {
 
  static propTypes = {
    input1: React.PropTypes.number.isRequired,
    input2: React.PropTypes.number.isRequired
  }
 
  render() {
    const { input1, input2 } = this.props;
 
    // some heavy computation
    const computedResult = heavyComputation(input1, input2);
 
    return (
      <div>
        {computedResult}
      </div>
    );
  }
 
}

In the example above if something triggers a re-render but input1 and input2 have still the same ref they had in the previous render the unnecessary heavyComputation will be completely avoid.

/buildo-react-pure/

    Package Sidebar

    Install

    npm i buildo-react-pure

    Weekly Downloads

    0

    Version

    1.0.1

    License

    ISC

    Last publish

    Collaborators

    • marcopiii
    • gabro
    • veej
    • giogonzo
    • tpetrucciani
    • malpenzibo
    • federico.ercoles