Skip to content Skip to sidebar Skip to footer

Reactjs: Compare Props And State On Shouldcomponentupdate

I want to check all properties and state if they are changed, return true if any changed and make a base component for all my root components. I'm wondering if it won't be the best

Solution 1:

It is considered best practice to compare props and state in shouldComponentUpdate to determine whether or not you should re-render your component.

As for why it's always evaluating to true, I believe your if statement isn't performing a deep object comparison and is registering your previous and current props and state as different objects.

I don't know why you want to check every field in both objects anyway because React won't even try to re-render the component if the props or state hasn't changed so the very fact the shouldComponentUpdate method was called means something MUST have changed. shouldComponentUpdate is much better implemented to check maybe a few props or state for changes and decide whether to re-render based on that.

Solution 2:

I think there's a problem in most of the tutorials I've seen (including the official docs) in the way that stores are accessed. Usually what I see is something like this:

// MyStore.jsvar _data = {};

varMyStore = merge(EventEmitter.prototype, {

  get: function() {
    return _data;
  },

  ...

});

When I used this pattern, I found that the newProps and newState in functions like shouldComponentUpdate always evaluate as equal to this.props and this.state. I think the reason is that the store is returning a direct reference to its mutable _data object.

In my case the problem was solved by returning a copy of _data rather than the object itself, like so:

get: function() {
    returnJSON.parse(JSON.stringify(_data));
  },

So I'd say check your stores and make sure you're not returning any direct references to their private data object.

Solution 3:

There is a helper function to do the comparison efficiently.

var shallowCompare = require('react-addons-shallow-compare');
exportclassSampleComponentextendsReact.Component {
  shouldComponentUpdate(nextProps, nextState) {
    returnshallowCompare(this, nextProps, nextState);
  }

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

Post a Comment for "Reactjs: Compare Props And State On Shouldcomponentupdate"