React.memoperforms a shallow comparison, so nested objects are not compared by their contents.It compares the references of object props using
Object.is().Example
jsxconst Child = React.memo(({ user }) => { console.log("Child rendered"); return <p>{user.profile.name}</p>; });Suppose the parent passes this object:
jsxconst user = { name: "John", profile: { name: "John Doe" } };Case 1: New outer object, same nested values
jsconst prevUser = { name: "John", profile: { name: "John Doe" } }; const nextUser = { name: "John", profile: { name: "John Doe" } };React compares the
userprop references:jsObject.is(prevUser, nextUser); // falseResult: The component re-renders because the outer object reference changed. React doesn't need to compare the nested properties.
Case 2: Same outer object, nested object changed
jsconst user = { name: "John", profile: { name: "John Doe" } }; const prevUser = user; user.profile.name = "Jane Doe"; const nextUser = user; Object.is(prevUser, nextUser); // trueResult:
React.memoconsiders theuserprop unchanged, because the outer object reference is the same.Even though the nested value changed, the shallow comparison doesn't detect it.
Note that mutating objects this way is generally discouraged in React because it can cause UI updates to be missed.
Remember this rule
Shallow comparison: Compares the outer prop values or references.
Deep comparison: Recursively compares nested object contents.
React.memo: Uses shallow prop comparison by default, not deep comparison.
In short,
React.memochecks whether theuserobject is the same object, not whether every property inside it is the same.
Comments
Post a Comment