Custom comparator
- React course
- Intermediate
- Lesson 31/80
- 4 min
Learn to write a custom comparator as the second argument.
Custom comparator
Sometimes shallow comparison isn't enough. For example, when the prop contains a deep object or you want to render only when one field changes. In this case, you give a comparator function as the second argument.
const MemoX = memo(X, (prev, next) => prev.user.id === next.user.id);. If the function returns true, render is skipped; if false, render runs.
This is powerful but dangerous: wrong comparison leads to bugs. Use only when really necessary; shallow comparison + useCallback is usually enough.
Deep compare danger
Some developers do deep comparison with JSON.stringify(prev) === JSON.stringify(next). This is slow; it stringifies the whole object on every render. Big objects cause serious performance loss.
A better method: compare only relevant fields. Like (prev, next) => prev.user.id === next.user.id && prev.theme === next.theme.
The best is to keep prop design simple. Passing primitives instead of deep objects both eases memo and improves readability. This design principle is often recommended in React.
Practice Custom comparator
Complete the skeleton. Write an Item component; take ({ '{ item }' }) and return <li>{ '{ item.name }' }</li>. Wrap with const MemoItem = memo(Item, (prev, next) => prev.item.id === next.item.id);. Export MemoItem.
Starter code
import { memo } from "react";
// Write Item and MemoItem hereSample solution
import { memo } from "react";
function Item({ item }) {
return <li>{item.name}</li>;
}
const MemoItem = memo(Item, (prev, next) => prev.item.id === next.item.id);
export default MemoItem;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the custom comparator return to skip render?
- null
- false
- undefined
- true Correct answer
Explanation: true skips render.
2 Comparator params
The comparator takes ____ parameters.
The comparator takes prev and next parameters.
Explanation: The answer: prev and next.
3 Match the custom comparator
| Term | Meaning |
|---|---|
prev/next |
parameters |
true |
skip |
false |
render |
field |
compare |