The Custom Comparison Function: arePropsEqual
What you'll learn: How to pass a second argument to React.memo when the default shallow comparison isn't sufficient for your component's props.
Beyond Shallow Comparison
By default, React.memo uses shallow equality (Object.is) to compare each prop. But sometimes you need custom logic—maybe you only care about certain properties of an object, or you need deep comparison for nested data.
React.memo accepts an optional second argument: a custom comparison function often called arePropsEqual.
How It Works
const MyComponent = React.memo(
function MyComponent({ user }) {
return <div>{user.name}</div>;
},
function arePropsEqual(prevProps, nextProps) {
// Return true if props are equal (skip re-render)
// Return false if props are different (re-render)
return prevProps.user.id === nextProps.user.id;
}
);
In this example, we only care if the user's id changed—not the entire object reference. If the id is the same, we return true to skip the re-render, even if the user object reference changed.
The Inverted Logic
Important quirk: This function is backwards from typical comparisons! Return true when props are equal (skip render), and false when they're different (do render). This trips up many developers.
When to Use It
- When you only care about specific properties of an object prop
- When shallow comparison is too strict for your use case
- When you understand the specific equality logic your component needs
Key Takeaway: Pass arePropsEqual as the second argument to React.memo to implement custom comparison logic, but remember it returns true to prevent re-renders and false to allow them.