1.0.1 • Published 8 years ago

buildo-react-pure v1.0.1

Weekly downloads
3
License
ISC
Repository
github
Last release
8 years ago

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.