Prop comparison
- React course
- Intermediate
- Lesson 30/80
- 4 min
Learn that React.memo does a shallow compare.
Prop comparison
React.memo by default does a shallow comparison across all props. Object.is(prev, next) is called for each prop; if all are equal, render is skipped.
Shallow comparison: primitives (number, string, boolean) by value; objects and arrays by reference. { '{ a: 1 }' } and { '{ a: 1 }' } are different references, not equal.
That's why useCallback and useMemo matter: when passing props to a child, they keep the reference stable. Without stabilization, React.memo always re-renders.
Object prop pitfall
If you pass an object prop like style={ '{ color: "red" }' } to a child, a new object is born on every render. React.memo detects this and re-renders the child.
The fix: wrap the object with useMemo or move it to module scope. const style = useMemo(() => ({ '{ color: "red" }' }), []); gives a stable reference.
Alternative: move constant objects outside the component. const RED_STYLE = { '{ color: "red" }' }; defined once at module scope; same reference in every render. This is the cleanest solution.
Practice UserCard memo
Complete the skeleton. Write a component called UserCard; take ({ '{ user, onSelect }' }) and return <li onClick={ '{ onSelect }' }>{ '{ user.name }' }</li>. Then wrap with const MemoUserCard = memo(UserCard);. Export MemoUserCard.
Starter code
import { memo } from "react";
// Write UserCard and MemoUserCard hereSample solution
import { memo } from "react";
function UserCard({ user, onSelect }) {
return <li onClick={onSelect}>{user.name}</li>;
}
const MemoUserCard = memo(UserCard);
export default MemoUserCard;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When are two objects equal in shallow compare?
- When contents equal
- Never
- When same reference Correct answer
- Always
Explanation: Equal when same reference.
2 useCallback's role
When passing a function prop to a React.memo child, use ____.
When passing a function prop to a React.memo child, use useCallback.
Explanation: Stabilized with useCallback.
3 Match the prop comparison steps
| Term | Meaning |
|---|---|
shallow |
default |
Object.is |
compare |
useCallback |
function |
useMemo |
object |