1

React documentation states that

shallowCompare returns true if the shallow comparison for props or state fails and therefore the component should update.

So, if is understand correctly, if there is no state in my component and i know there are no changes in the props keys, this code

let shallowDiff = Object.keys(this.props).filter((item) => {
        return this.props[item] !== nextProps[item];
});
return shallowDiff.length !== 0;

should return the same as the react comparison. But it doesn't. If there are no changes, my code correctly returns an empty array, whereas react returns true. I am trying to understand this behavior and searching a way to search the problem-key, but i just do not get it.

devsteff
  • 108
  • 1
  • 7
  • https://stackoverflow.com/questions/36084515/how-does-shallow-compare-work-in-react – codemax Aug 17 '17 at 08:35
  • Read it before, but the Problem is the same - the code provided by me should do exactly that, and it does, but react does not. So, what does react? – devsteff Aug 17 '17 at 08:47

1 Answers1

1

shallowCompare is a legacy add-on. Use React.PureComponent instead. https://facebook.github.io/react/docs/shallow-compare.html

If there are no changes in state or props, shallowCompare returns false. And of course, when there are changes, shallowCompare returns true, and proceeds with the re-render of the Component.

But if you have a deeply nested object, shallowCompare will not be able to tell that the nested objects have updated/changed.

You either write your own function to check if the object has changed, or you can use a very naive method to check for changes if the ORDER of the properties is NOT important.

JSON.stringify(obj1) === JSON.stringify(obj2) 

I personally don't recommend using the shallowCompare or React.PureComponent because the use case is too narrow. If you have a complex object, neither function is effective. If your function works for you, then use it.

codemax
  • 1,322
  • 10
  • 19