I know this question has been discussed so many times, and I think I got a basic idea. There are some top rated answers I found from StackOverflow:
A shallow copy of an object (or array) is a separate object with a matching set of property names and property values.
After making a shallow copy, a comparison on a property-by-property basis of the two objects (the original and the copy) will show all property values being ===
.
For example:
let o1 = { a: 1, b: 2, c: { x: "hello", y: "world" } };
let o2 = {};
Object.keys(o1).forEach(propertyName => o2[propertyName] = o1[propertyName]);
Now if the property values of o1 and o2 are compared, they are of course ===
. In particular, property "c" of both objects will be a reference to that sub-object with "x" and "y" property names. However, comparing o1
and o2
with either ==
or ===
will not show equality, because two distinct objects are never ==
to each other regardless of their contents.
A deep copy of an object is one where every object-valued property of the source is recursively deep-copied into the destination copy. Because new object values are of necessity created for the deep-copy target, those property values will not compare as ===
, because no two distinct objects can be ===
.
Making deep copies in a language like JavaScript can be problematic because the "graph" of references from property values can be circular, and because some property values may be functions. Generally a deep copy method has to make some assumptions on an application by application basis.
In my experience, the need to make a deep copy of an object is quite rare compared to making shallow copies.
Now, all that aside, comparison between two object references as in your bit of React code:
shouldComponentUpdate(nextProps) {
return this.props.children !== nextProps.children;
}
has nothing to do with shallow or deep copies. That's a single comparison between two object properties, both named "children". The objects referenced by this.props
and nextProps
may be different objects or they may be the same object, and one may be a shallow or deep copy of the other, but that makes no difference for that comparison statement: all that's doing is comparing the two particular "children" property values for strict inequality. (It's true that if nextProps
happens to be a shallow copy of this.props
, or vice-versa, that !==
comparison would be false, but the comparison doesn't have to know about the prior history of the two objects; it's just a single comparison of two values.)