Sub topic 11
Cheap Change Detection with Reference Equality
This chapter assumes you know how JavaScript compares primitives and references, and that you can write immutable updates with spread syntax, map, and filter. It also builds on structural sharing from the previous chapter, which copies only the objects along a changed path and reuses everything else. Here you will see the main reason immutable data matters in practice. It lets you answer "did anything change?" with one comparison.
The Change Detection Problem
Many parts of a program need to know whether data has changed. A UI component decides whether to re-render. A cache decides whether a stored result is still valid. A sync layer decides whether to send an update to the server.
If data can be mutated in place, the only reliable way to answer that question is to compare the contents. You walk both values, compare every property, and recurse into every nested object and array. This is a deep equality check. Its cost grows with the size of the data, and you pay it on every check, even when nothing changed.
Immutable updates turn this around. When every change produces a new object, and unchanged parts are shared, a changed reference means "something inside changed" and an unchanged reference means "nothing inside changed". You compare two pointers instead of two trees.
How Reference Equality Works
The === operator compares objects by identity, not by contents. Two objects are equal only if they are the same object in memory.
const a = { count: 1 };
const b = { count: 1 };
const c = a;
console.log(a === b); // false: same contents, different objects
console.log(a === c); // true: same objectThis comparison takes constant time, whether the object has one property or one million. The engine compares two references and nothing else.
Object.is behaves like === for objects. It differs only for two primitive edge cases: Object.is(NaN, NaN) is true and Object.is(0, -0) is false. React and many state libraries use Object.is so that a NaN value does not count as "changed" on every comparison.
console.log(NaN === NaN); // false
console.log(Object.is(NaN, NaN)); // true
console.log(0 === -0); // true
console.log(Object.is(0, -0)); // falseThe Contract That Makes It Work
Reference equality is only a valid change test if your code follows one rule. Never mutate a value that someone else might compare later. When you follow the rule, two facts hold:
- If
prev === next, nothing changed anywhere inside, because changing anything would have required a new object along the path. - If
prev !== next, something along that path was replaced. With structural sharing, you can then compare child references to find exactly which branch changed.
Here is that drill-down with real state:
const state = {
user: { name: 'Ada', address: { city: 'London' } },
settings: { theme: 'dark' }
};
const next = {
...state,
user: {
...state.user,
address: { ...state.user.address, city: 'Paris' }
}
};
console.log(next === state); // false: root changed
console.log(next.settings === state.settings); // true: skip settings
console.log(next.user === state.user); // false: look inside user
console.log(next.user.address === state.user.address); // false: address changedCode that renders settings can skip its work entirely. Only the code that depends on user.address needs to run again.
Memoization with Reference Checks
Memoization means caching a function's result and reusing it when the inputs are the same. With immutable inputs, "the same" can mean "the same reference". The helper below remembers only the most recent call, which is the pattern most selector libraries use.
function memoizeLast(fn) {
let lastArgs = null;
let lastResult;
return (...args) => {
if (
lastArgs !== null &&
args.length === lastArgs.length &&
args.every((arg, i) => Object.is(arg, lastArgs[i]))
) {
return lastResult;
}
lastArgs = args;
lastResult = fn(...args);
return lastResult;
};
}
let calls = 0;
const selectDone = memoizeLast(todos => {
calls += 1;
return todos.filter(t => t.done);
});
const todos = [
{ id: 1, text: 'Write', done: true },
{ id: 2, text: 'Review', done: false }
];
selectDone(todos);
selectDone(todos);
console.log(calls); // 1: same reference, cached result reused
const updated = todos.map(t => (t.id === 2 ? { ...t, done: true } : t));
selectDone(updated);
console.log(calls); // 2: new reference, recomputedThe memoized function also returns the same array reference when its input has not changed. That matters because downstream code can then use reference checks on the result too. Stable references flow through the whole pipeline.
Shallow Equality: One Level Deeper
Sometimes you receive a fresh container whose contents are the same references as before. Function arguments and component props are common cases: the props object is new on every call, but each prop value might be unchanged. Shallow equality compares the top-level keys with Object.is and does not recurse.
function shallowEqual(a, b) {
if (Object.is(a, b)) return true;
if (
typeof a !== 'object' || a === null ||
typeof b !== 'object' || b === null
) {
return false;
}
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
return keysA.every(
key => Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key])
);
}
const settings = { theme: 'dark' };
const user = { name: 'Ada' };
console.log(shallowEqual({ user, settings }, { user, settings })); // true
console.log(shallowEqual({ user, settings }, { user: { ...user }, settings })); // falseShallow equality costs time proportional to the number of keys, not the size of the whole tree. It is the comparison behind React.memo and PureComponent, and the reason those tools work well with immutable state.
| Check | Cost | Correct when | Typical use |
|---|---|---|---|
| `===` / `Object.is` | Constant | Data is updated immutably | State roots, selector inputs, hook dependencies |
| Shallow equality | Number of top-level keys | Values inside are updated immutably | Props objects, argument lists |
| Deep equality | Size of the whole structure | Always, even with mutation | Tests, rare one-off comparisons |
Failure Mode 1: Mutation Hides Changes
If code mutates in place, the reference stays the same while the contents change. Every reference check then reports "no change", and cached results go stale. This is a false negative, and it is the most common bug in this area.
let computeCount = 0;
const countDone = memoizeLastSingle(list => {
computeCount += 1;
return list.filter(t => t.done).length;
});
function memoizeLastSingle(fn) {
let lastArg;
let lastResult;
let hasRun = false;
return arg => {
if (hasRun && Object.is(arg, lastArg)) return lastResult;
hasRun = true;
lastArg = arg;
lastResult = fn(arg);
return lastResult;
};
}
const list = [{ id: 1, done: false }];
console.log(countDone(list)); // 0
list[0].done = true; // mutation: same array, same item reference
console.log(countDone(list)); // still 0: stale cached result
console.log(computeCount); // 1: the function never re-ranIn a UI, the same bug shows up as a screen that does not update after a click. The data changed, but nothing noticed. Mutating methods such as push, sort, and splice cause this just as easily as direct assignment.
Failure Mode 2: Needless New References
The opposite bug is a false positive. Code creates a new object or array even though the contents are the same, so every check reports "changed" and the caching does nothing.
const items = [{ id: 1, done: true }];
// Returns a new array on every call, even with identical input
const getDone = list => list.filter(t => t.done);
console.log(getDone(items) === getDone(items)); // falseCommon sources include:
- Calling
filter,map, or spread inside a render or selector without memoizing it. - Writing an object or array literal inline as a prop or dependency, such as
style={{ color: 'red' }}. - Defining callback functions inline, since each function expression creates a new function.
- Update functions that always return a copy, even when the new value equals the old one.
The last case is easy to fix at the source. Return the original object when nothing would change:
function setTheme(settings, theme) {
if (settings.theme === theme) return settings; // keep the reference stable
return { ...settings, theme };
}
const s = { theme: 'dark' };
console.log(setTheme(s, 'dark') === s); // true
console.log(setTheme(s, 'light') === s); // falsemap has a similar trap. It always returns a new array, even if the callback returns every item unchanged. If a no-op update is likely, check first and return the original array.
Where You Will Meet This
Reference equality is built into many tools you already use:
- React compares state with
Object.isto decide whether to re-render, and compares hook dependency arrays item by item withObject.isforuseMemo,useCallback, anduseEffect. - Redux and its
useSelectorhook re-render a component only when the selected value's reference changes. Reselect memoizes selectors by input references. - Immer, covered in the next chapter, returns the original object when a recipe makes no changes, and it shares untouched branches. Both behaviors keep references stable for you.
None of these tools inspect your data deeply. They trust you to follow the immutability contract.
Exercise
A selector is memoized on its input reference. After a user toggles a todo, the screen does not update. The toggle code is state.todos.find(t => t.id === id).done = true; setState(state);. Explain why the screen stays the same and rewrite the update so change detection works.
Show answer
The code mutates a todo in place and passes the same state object back, so Object.is(prev, next) is true and both the state check and the selector's input check report "no change". Create new references along the changed path instead: setState({ ...state, todos: state.todos.map(t => (t.id === id ? { ...t, done: true } : t)) });. Now the state, the todos array, and the toggled todo are new, while the other todos keep their references.
Exercise
A component wrapped in React.memo receives options={{ sort: 'asc' }} and items={allItems.filter(i => i.visible)} from its parent. It re-renders every time the parent renders, even when nothing changed. Name the cause and two fixes.
Show answer
Both props are new references on every parent render: the object literal creates a new object and filter creates a new array. Shallow equality compares them with Object.is, so they always look changed. Fix the options by defining the object once outside the component, or wrapping it in useMemo. Fix the items by memoizing the filtered array with useMemo keyed on allItems, or by using a memoized selector, so the reference stays stable while allItems is unchanged.
Exercise
Why does Object.is give a better change test than === when a value might be NaN?
Show answer
NaN === NaN is false, so a value that stays NaN would be reported as changed on every check, causing needless recomputation. Object.is(NaN, NaN) is true, so an unchanged NaN is correctly treated as unchanged.