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.
@pureComponent { 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!
@pureComponent static propTypes = input1: ReactPropTypesnumberisRequired input2: ReactPropTypesnumberisRequired { const input1 input2 = thisprops; // some heavy computation const computedResult = ; 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.