0

I cam across the definition of a component in the code base I'm working upon:

@PureRender
export default class UiWidget extends Component {
}

I tried googling to understand the significance of the attribute @PureRender which has been used to decorate the component but didn't get any relevant link. Can someone help me understand the impact of applying this attribute on a reactJs component?

RBT
  • 24,161
  • 21
  • 159
  • 240

2 Answers2

4

There are three ways to define a react component:

  1. Functional stateless component which doesn't extend any class
  2. A component that extends PureComponent class
  3. A normal component that extends Component class

For simple, presentation-only components that need to be easily reused, stateless functional components are preferred.

PureComponent overrides the shouldComponentUpdate for you and re-renders the component only if the props or state have actually changed. The important point here is it only does a shallow comparison of nextProps and nextState. You can read more here and here. @PureRender is simply the declarative way of saying that my reactJs component inherits from predefined PureComponent reactJs component.

Extending Component class helps to implement your own shouldComponentUpdate if you need some performance gains by performing you custom comparison logic between next/current props and state.

Community
  • 1
  • 1
Richa Garg
  • 1,888
  • 12
  • 23
  • So decorating a custom component (which inherits from `Component`) with `@PureRender` attribute and a component which inherits from `PureComponent` defined in reactJs library is one and the same thing. Is it? Can you please share some details about `@PureRender` attribute in your post which is my primary question. – RBT May 03 '17 at 01:24
  • Yes. it is one and the same thing. You can look at an example here https://github.com/brigand/react-purerender – Richa Garg May 03 '17 at 04:58
3

This is a javascript decorator, originally proposed in ES2016 (ES7). I believe they were removed from the proposal and postponed.

The purpose of the decorator is to add shouldComponentUpdate implementation with shallow property comparison.

Nowadays the same is done using extension from PureComponent:

export default class UiWidget extends React.PureComponent

I believe the decorator is not part of React, therefore it is probably implemented somewhere in your project, or in a dependency, similar to pure-render-decorator.

Historically, React implemented that using pure-render-mixin, however mixins couldn't be used with ES6 classes (only with React.createClass) therefore alternative solutions were introduced. Decorators were one of them.

Sulthan
  • 128,090
  • 22
  • 218
  • 270