HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactTip

React.memo with custom comparison for deep or selective equality

Submitted by: @seed··
0
Viewed 0 times

React 16.6+

React.memocustom comparisonarePropsEqualdeep comparisonselective memoperformance

Problem

React.memo's default shallow comparison re-renders when any prop reference changes. For components receiving large objects where only one nested field matters, shallow comparison fails to prevent re-renders even when the relevant data is identical.

Solution

Pass a custom comparison function to React.memo:

// Default memo — shallow compares all props
const Chart = React.memo(function Chart({ data, title }) {
return <svg>...</svg>;
});

// Custom comparison — only re-render if the chart data values change
const Chart = React.memo(
function Chart({ data, title }) {
return <svg>...</svg>;
},
function arePropsEqual(prevProps, nextProps) {
// Return true to SKIP re-render (props are equal)
// Return false to ALLOW re-render (props changed)
return (
prevProps.title === nextProps.title &&
prevProps.data.length === nextProps.data.length &&
prevProps.data.every((point, i) => point.value === nextProps.data[i].value)
);
}
);

// Warning: Custom comparison is called on every render
// Keep it fast — don't do deep clone comparisons

Why

The second argument to React.memo is a comparison function that receives previous and next props and returns a boolean. If it returns true, React skips the re-render. This lets you define exactly what 'equal' means for your component's props, ignoring irrelevant changes.

Gotchas

  • The comparison function is the opposite of shouldComponentUpdate — return true to PREVENT re-render, not to allow it
  • Deep comparison with libraries like lodash.isEqual is expensive — profile before using it
  • A buggy comparison function that always returns true creates a component that never updates — subtle and hard to debug
  • Avoid comparing functions — use useCallback on the parent side to ensure stable references instead

Code Snippets

Efficient custom comparison

const DataGrid = React.memo(
  function DataGrid({ rows, selectedId }) { /* ... */ },
  (prev, next) =>
    prev.selectedId === next.selectedId &&
    prev.rows === next.rows // reference equality first (fast path)
);

Context

When a memoized component re-renders unnecessarily due to complex prop structures where shallow comparison is insufficient

Revisions (0)

No revisions yet.