Sub topic 11
Custom comparison functions and their risks
This chapter assumes you know function components, useState, and props. It also assumes you understand referential equality and the default shallow comparison that React.memo performs. You should be comfortable with why inline objects and functions break memo.
What a custom comparison function is
By default, memo compares each prop with Object.is. If every prop is identical, React reuses the previous result and skips the render. You can replace that check by passing a function as the second argument to memo.
import { memo } from 'react';
const UserCard = memo(
function UserCard({ user, onSelect }) {
return <button onClick={() => onSelect(user.id)}>{user.name}</button>;
},
(prevProps, nextProps) =>
prevProps.user.id === nextProps.user.id &&
prevProps.user.name === nextProps.user.name &&
prevProps.onSelect === nextProps.onSelect
);The function receives the previous props and the next props. It returns true if the two sets are equal, which means React skips the render. It returns false if they differ, which means React renders.
This is the opposite of shouldComponentUpdate in class components, which returned true to re-render. Mixing up the return value is a common mistake. A comparison that always returns true freezes the component. One that always returns false makes memo do nothing.
// Never re-renders after the first render, whatever the props are.
const Frozen = memo(Component, () => true);
// Re-renders every time, the same as no memo plus the comparison cost.
const Always = memo(Component, () => false);When a custom comparison is reasonable
The default comparison fails when a parent creates a new object on each render but the contents are the same. For example, a parent may build a user object from API data every time. A custom comparison can look at the fields that matter.
Reach for it only after you have measured, and only when you cannot fix the cause in the parent. These alternatives are usually better:
- Stabilize the prop in the parent with
useMemooruseCallback. - Pass primitive values (
user.id,user.name) instead of the whole object. - Move state down so the parent renders less often.
Passing primitives is often the simplest fix. The default shallow comparison handles strings and numbers correctly, and you write no comparison code.
import { memo } from 'react';
const UserCard = memo(function UserCard({ id, name, onSelect }) {
return <button onClick={() => onSelect(id)}>{name}</button>;
});
// Parent usage:
// <UserCard id={user.id} name={user.name} onSelect={handleSelect} />A custom comparison makes sense when you cannot change the parent, such as a third-party component or a shared component with many callers. It also helps when the prop is a large object and only a few fields affect the output.
The main risk: stale output
The comparison function decides whether the output can change. If it ignores a prop that the component uses, the component shows old data. React will not warn you.
Here is a broken version:
import { memo, useState } from 'react';
const Badge = memo(
function Badge({ label, color }) {
return <span style={{ color }}>{label}</span>;
},
// Bug: color is not compared.
(prev, next) => prev.label === next.label
);
export function Demo() {
const [color, setColor] = useState('red');
return (
<>
<button onClick={() => setColor('blue')}>Make blue</button>
<Badge label="Status" color={color} />
</>
);
}Clicking the button changes color, but the badge stays red. The comparison says the props are equal because label did not change. The bug stays hidden until someone changes only color.
The fix is to compare every prop that affects the output:
(prev, next) => prev.label === next.label && prev.color === next.colorFunctions are props too
The most frequent form of this bug is skipping function props. A developer sees that onSelect changes on every render and leaves it out of the comparison to keep memo effective. The component then holds a stale version of the function.
import { memo, useState } from 'react';
const Row = memo(
function Row({ id, onSelect }) {
return <li onClick={() => onSelect(id)}>Row {id}</li>;
},
// Bug: onSelect is ignored.
(prev, next) => prev.id === next.id
);
export function List() {
const [mode, setMode] = useState('view');
// This closure reads `mode`. A new function is created each render.
const onSelect = (id) => console.log(mode, id);
return (
<>
<button onClick={() => setMode('edit')}>Edit mode</button>
<ul>
<Row id={1} onSelect={onSelect} />
<Row id={2} onSelect={onSelect} />
</ul>
</>
);
}After you click the button, the rows still call the first onSelect, so they log view instead of edit. The rows never re-rendered, so their click handlers still close over the old mode.
The code example at the start of this chapter compares onSelect for this reason. If you want the comparison to stay cheap and correct, wrap the function in useCallback in the parent so the reference stays stable. Then you do not need to exclude it from the comparison.
Other risks
Deep comparison cost
A custom comparison runs on every parent render, for every instance of the component. If it does a deep equality check on a large object, the check can cost more than the render it avoids. A deep comparison also has to handle cycles, dates, maps, and functions, and a library helper may not cover all of them.
Prefer comparing a small number of fields. If you need a deep comparison, measure it in the Profiler first.
Mutation defeats comparison
Both the default and custom comparisons assume you do not mutate objects. If you change user.name in place and pass the same user reference, a reference check sees no change.
// Bug: same reference, new content.
user.name = 'Ada';
setUser(user);React may not even re-render the parent in this case, because setUser receives the same reference. Always create a new object for updates:
setUser({ ...user, name: 'Ada' });A field-by-field comparison, like the one in UserCard, would catch a changed name only if the parent re-renders and passes the mutated object. Do not rely on this. Treat props and state as immutable.
Maintenance drift
A comparison function lists props by name. When someone adds a new prop to the component, the comparison does not update itself. If the author forgets to add the prop to the comparison, the new prop is silently ignored. This is the same stale-output bug, introduced later by a different person.
You can reduce the risk by comparing all keys generically and special-casing only the ones that need it:
import { memo } from 'react';
function areEqualExcept(ignored) {
return (prev, next) => {
const keys = new Set([...Object.keys(prev), ...Object.keys(next)]);
for (const key of keys) {
if (ignored.includes(key)) continue;
if (!Object.is(prev[key], next[key])) return false;
}
return true;
};
}
const Panel = memo(
function Panel({ title, items, onClose }) {
return (
<section>
<h2>{title}</h2>
<p>{items.length} items</p>
<button onClick={onClose}>Close</button>
</section>
);
},
areEqualExcept(['onClose'])
);New props are compared automatically. You still must decide whether ignoring onClose is safe, and it is safe only if that function never depends on values that change.
Context and state bypass the comparison
A custom comparison only controls re-renders caused by a parent passing new props. It does not stop a re-render caused by the component's own state or by a context it reads. If the component calls useContext, a context change renders it even when your comparison returns true.
import { memo, useContext } from 'react';
import { ThemeContext } from './ThemeContext';
const Title = memo(
function Title({ text }) {
const theme = useContext(ThemeContext);
return <h1 className={theme}>{text}</h1>;
},
() => true
);Even with a comparison that always returns true, Title updates when the theme changes. That behavior is correct, but it means a comparison function is not a general "never render" switch.
How the comparison fits into a render
Decision checklist
Before writing a custom comparison, work through these questions in order.
| Question | If yes |
|---|---|
| Did the Profiler show this component as a real cost? | Continue. Otherwise do nothing. |
| Can the parent pass primitives or stable references instead? | Do that and keep the default comparison. |
| Can state move down or the content move into `children`? | Do that instead. |
| Does the comparison cover every prop the output uses, including functions? | Required before you ship it. |
| Is the comparison cheaper than the render it skips? | Verify in the Profiler. |
Testing a comparison function
Because the failure mode is silent, test the comparison directly. Pull it out as a named function and check the cases that matter.
export function areUserCardPropsEqual(prev, next) {
return (
prev.user.id === next.user.id &&
prev.user.name === next.user.name &&
prev.onSelect === next.onSelect
);
}
// Example checks (run with any test runner):
const base = { user: { id: 1, name: 'Ada' }, onSelect: () => {} };
console.assert(
areUserCardPropsEqual(base, { ...base, user: { id: 1, name: 'Ada' } }) === true,
'same fields in a new object should be equal'
);
console.assert(
areUserCardPropsEqual(base, { ...base, user: { id: 1, name: 'Bo' } }) === false,
'a changed name should not be equal'
);
console.assert(
areUserCardPropsEqual(base, { ...base, onSelect: () => {} }) === false,
'a new function reference should not be equal'
);Add a test whenever you add a prop. A failing test is much easier to find than stale output in production.
Summary
- The comparison function returns
truewhen props are equal, which skips the render. - It must compare every prop the output depends on, including functions.
- It runs on every parent render, so keep it cheaper than the render it replaces.
- It cannot stop renders caused by the component's own state or by context.
- Prefer primitives, stable references, and moving state down before you write one.
Exercise
A teammate writes memo(Chart, (prev, next) => prev.data === next.data). Chart also takes a color prop and renders it. The color picker in the parent changes, but the chart does not update. What is the cause, and how do you fix it?
Show answer
The comparison ignores color, so it returns true when only color changes and React reuses the old output. Compare every prop that affects the output: (prev, next) => prev.data === next.data && prev.color === next.color. Or remove the custom comparison and use the default shallow comparison, which checks all props.
Exercise
A custom comparison on Title always returns true, and Title reads a theme with useContext. The user switches from light to dark. Does Title update, and why?
Show answer
Yes. The comparison only decides whether to skip a render caused by new props from the parent. A context change that the component reads triggers a render directly, so the comparison is not consulted for it.
Exercise
Why can a deep-equality custom comparison make performance worse, and what is a cheaper option?
Show answer
The comparison runs on every parent render for every instance. On a large object the deep check can cost more than rendering the component. Cheaper options are to compare only the few fields that affect the output, pass primitive props so the default shallow comparison works, or stabilize the object in the parent with useMemo.