2

Is there a way to see the difference between this.state and nextState?

In:

shouldComponentUpdate(nextProps, nextState){
  //here
}

I would like to see the difference between those states. Does React have a handy way to do it? If not, I'll have to iterate those 2 objects and compare them.

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
pmiranda
  • 7,602
  • 14
  • 72
  • 155
  • Take a look at [Object comparison in JavaScript](https://stackoverflow.com/questions/1068834/object-comparison-in-javascript) – Dupocas Dec 10 '19 at 18:44
  • Do you want to check if there is any difference or you want to know the exact changes? – Vaibhav Singh Dec 10 '19 at 18:46
  • Does this answer your question? [Object comparison in JavaScript](https://stackoverflow.com/questions/1068834/object-comparison-in-javascript) – Agney Dec 10 '19 at 18:46
  • @VaibhavSingh the exact changes. I want to avoid the rerender with `shouldComponentUpdate` depending on which state (or props) has changed. I know I can use libraries for compare 2 objects, I was asking if React has a feature for this. – pmiranda Dec 10 '19 at 19:11
  • @pmiranda short answer - no – Bakhtiiar Muzakparov Dec 10 '19 at 20:24
  • Your component is visual output of the state, why won't you want to re render if state changed? If you store data that is not relevant to be rendered then store it in `this.anyOtherPropYouCanThiinkOf`. – HMR Dec 10 '19 at 21:34
  • The code that I'm working on is weird. It's a big component with a lot of childrens and their childrens. I need to re-render only some childrens but not the entire big component (parent), because it's children uses local states that I'm loosing with those re-renders. Solutions sounds obvious like using a store instead those local states (this app has Redux so that's what I'm going to do today) but I'm talking about 120 different componentes with local states, and only in some cases from props (I'm passing states to props in some cases) the parent components need to be rendered – pmiranda Dec 11 '19 at 12:37
  • The actual code (not mine) is passing data through props to each childrens, and their childrens. This data come the storage from Redux, but it's not complete. Would be hard and I don't have much time to pass those local states to redux. – pmiranda Dec 11 '19 at 12:39

1 Answers1

3

This is my usually code, i use Lodash

isEqual

to Performs a deep comparison between two values to determine if they are equivalent.

shouldComponentUpdate(nextProps, nextState) {
        console.log(this.state.data, nextState.data);
        console.log(_.isEqual(this.state.data, nextState.data));
        return (
            !_.isEqual(this.state.filterFields, nextState.filterFields) ||
            !_.isEqual(this.state.data, nextState.data) ||
            !_.isEqual(this.props.collection, nextProps.collection) ||
            !_.isEqual(this.props.service, nextProps.service)
        );
    }
Igris Dankey
  • 383
  • 2
  • 6