Sub topic 11
Cheap Change Detection with Reference Equality
This chapter assumes you know how spread copies work, how nested immutable updates copy only the changed path, and what structural sharing means. With those in place, immutability gives you something useful: you can tell whether data changed with a single === comparison.
The core idea
Comparing two objects for equal content means walking every property, recursively. That deep comparison costs time in proportion to the size of the data. Reference equality (=== on objects) only asks whether two variables point to the same object, and it takes constant time no matter how large the object is.
Mutation makes === useless for change detection, because a changed object is still the same object. Immutable updates make it reliable. If something changed, it is a new object. If nothing changed, it is the same object.
const state = {
user: { name: 'Ada' },
todos: [{ id: 1, done: false }, { id: 2, done: false }]
};
function toggleTodo(state, id) {
return {
...state,
todos: state.todos.map(t => (t.id === id ? { ...t, done: !t.done } : t))
};
}
const next = toggleTodo(state, 1);
console.log(next === state); // false: the root changed
console.log(next.todos === state.todos); // false: the todos branch changed
console.log(next.user === state.user); // true: the user branch was shared
console.log(next.todos[1] === state.todos[1]); // true: untouched todo reusedEach === answers "did anything under here change?" for one whole subtree. Code that only cares about user can skip work as soon as it sees next.user === state.user.
Using it: memoizing derived data
UI libraries rely on this pattern. React's memo and useMemo, Redux selectors, and Reselect all compare inputs by reference. Here is a minimal version:
function memoizeOne(fn) {
let called = false;
let lastArg;
let lastResult;
return arg => {
if (called && arg === lastArg) return lastResult;
called = true;
lastArg = arg;
lastResult = fn(arg);
return lastResult;
};
}
let runs = 0;
const countDone = memoizeOne(todos => {
runs++;
return todos.filter(t => t.done).length;
});
const todos = [{ id: 1, done: false }];
countDone(todos);
countDone(todos); // same reference: cached
countDone([...todos, { id: 2, done: true }]); // new array: recomputed
console.log(runs); // 2Common errors
Reference equality only works when every update follows immutable rules. Breaking those rules causes one of two failure modes.
| Mistake | What `===` reports | Effect |
|---|---|---|
| Mutating in place | "unchanged" when data did change | Stale UI, cached results never refresh |
| Creating a new object for a no-op update | "changed" when nothing changed | Wasted recomputation and re-renders |
The first mistake is the worse of the two, because it produces wrong results:
const list = [{ id: 1, done: false }];
const previous = list;
list[0].done = true; // mutation
console.log(previous === list); // true: the change is invisibleThe second mistake is subtler. An update function that always spreads returns a new reference even when the value is identical. Return the original when nothing changes:
function setName(state, name) {
if (state.user.name === name) return state; // no-op keeps the reference
return { ...state, user: { ...state.user, name } };
}
const s1 = { user: { name: 'Ada' } };
console.log(setName(s1, 'Ada') === s1); // true
console.log(setName(s1, 'Grace') === s1); // falseExercise
A component re-renders only when props.items !== prevProps.items. After state.items.push(newItem), the new item does not appear. Explain why, and give a fix.
Show answer
push mutates the existing array, so state.items is still the same reference and the !== check returns false. The component skips the render. Fix it by creating a new array, for example state = { ...state, items: [...state.items, newItem] }, so the reference changes.
Exercise
A function clearFilter(state) always returns { ...state, filter: '' }. Why can this cause unnecessary work, and how would you change it?
Show answer
It returns a new root object even when filter is already empty, so every reference check on the root reports a change. Add a guard: if (state.filter === '') return state; before building the new object.