Noitidart
Noitidart

Reputation: 37228

How to compare prevProps with this.props in shouldComponentUpdate

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?

Upvotes: 6

Views: 18245

Answers (2)

wintvelt
wintvelt

Reputation: 14101

React does not provide deep comparison of objects out of the box.

You could build something yourself for this. E.g by adding and maintaining 1 unique ID to your object to register changes.

Or use a library like immutableJS consistently across your app. Worthwhile for large complex app with large complex objects.

To make sure: for the functionality of your app, you should not need shouldComponentUpdate(). React has its own engine that only renders differences between states.

Upvotes: 3

Ori Drori
Ori Drori

Reputation: 191916

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');
  }
});

Upvotes: 6

Related Questions