Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare prevProps with this.props in shouldComponentUpdate

Tags:

reactjs

I am now using shouldComponentUpdate but I cannot simply do prevProps.myPropObj == this.state.props.myPropObj to compare. It is an object and I would need to do deep compare. Does react expose to me some method to tell me if my prop changed or not? Or do they expect me to do the deep comparison myself? I was thinking react specializes in this comparison so it should tell us true/false on if same or not no?

like image 847
Noitidart Avatar asked Apr 20 '16 12:04

Noitidart


1 Answers

If the props are immutable, you can use react's shallowCompare. The props can be immutable if you use something like immutablejs, or you change the objects by replacing and not mutating them, for example const prop = Object.assign({}, prop, { changedValues: 'value' });

var shallowCompare = require('react-addons-shallow-compare');
export class SampleComponent extends React.Component {
  shouldComponentUpdate(nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState);
  }

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

For non-es6, non-node environment:

The equivalent of var shallowCompare = require('react-addons-shallow-compare'); is var shallowCompare = React.addons.shallowCompare; so complete example would be:

var SampleComponent = React.createClass({
  shouldComponentUpdate: function(nextProps, nextState) {
     return React.addons.shallowCompare(this, nextProps, nextState);
  },
  render: function() {
     return React.createElement('div', {className:this.props.className}, 'foo');
  }
});
like image 115
Ori Drori Avatar answered Oct 01 '22 22:10

Ori Drori