Custom Comparison Functions
What you'll learn: How to provide your own equality logic to React.memo when shallow comparison isn't enough.
Why Custom Comparisons?
By default, React.memo uses shallow equality to compare props—it checks if each prop reference is the same. But sometimes you need deeper or more selective comparison logic. Maybe you only care about specific props, or you need to compare nested object values instead of references.
React.memo accepts a second argument: a custom comparison function that lets you define exactly when a component should skip re-rendering.
The Signature
const MemoizedComponent = React.memo(Component, (prevProps, nextProps) => {
// Return true to SKIP re-render (props are "equal")
// Return false to allow re-render (props changed)
});
Important: This is inverted from typical comparison logic! Return true when props are the same, false when they differ.
Example: Compare Only Specific Props
const ExpensiveChart = React.memo(
({ data, theme, onHover }) => {
// Render chart...
},
(prevProps, nextProps) => {
// Only re-render if data changed; ignore theme/onHover
return prevProps.data === nextProps.data;
}
);
Example: Deep Equality on Nested Objects
import isEqual from 'lodash/isEqual';
const DeepMemoized = React.memo(
MyComponent,
(prevProps, nextProps) => {
return isEqual(prevProps.user, nextProps.user);
}
);
Here you're comparing the contents of user objects, not just their references.
When to Use This
- You need to ignore certain props (like callbacks)
- You must compare nested object values
- Shallow equality causes false-positive re-renders
Key Takeaway: Custom comparison functions give you fine-grained control over React.memo, letting you implement deep equality or selective prop checks—but use them sparingly, as the comparison itself has a cost.