devsteff devsteff - 9 months ago 73
React JSX Question

How does React shallowCompare work?

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download