Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PureRenderMixin in an ES6 React component

Is there any way to include a mixin in a React ES6 class component? (i.e extends React.Component)? If so, what is the official way of doing it?

I'd like to include PureRenderMixin in one of my components that has an immutable state to speed up the diffing process.

like image 705
David Xu Avatar asked Aug 21 '15 20:08

David Xu


1 Answers

https://facebook.github.io/react/docs/shallow-compare.html

shallowCompare is a helper function to achieve the same functionality as PureRenderMixin while using ES6 classes with React.

import shallowCompare from 'react-addons-shallow-compare';

export default class SampleComponent extends React.Component {

  shouldComponentUpdate(nextProps, nextState) {
    // pure render
    return shallowCompare(this, nextProps, nextState);
  }

  render() {
    return <div className={this.props.className}>foo</div>;
  }
}

Source code of PureRenderMixin is:

var ReactComponentWithPureRenderMixin = {
  shouldComponentUpdate: function(nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState);
  },
};

So, when You use PureRenderMixin, You actually use shallowCompare

UPDATE 15.3.0:

Add React.PureComponent - a new base class to extend, replacing react-addons-pure-render-mixin now that mixins don't work with ES2015 classes.

like image 55
Bohdan Lyzanets Avatar answered Oct 13 '22 15:10

Bohdan Lyzanets