Full answer
Shallow equality answers: are these two objects made of the same values at the first level? Implementation steps:
- If
Object.is(a, b), return true. It handles the same reference,NaN, and distinguishes+0from-0. - If either is not an object or is
null, return false. - Compare the number of own enumerable keys.
- For each key of
a, check thatbhas it as its own property (Object.hasOwn) and thatObject.is(a[key], b[key]). The own property check matters when a value isundefined.
Why libraries use it: React's memo, PureComponent, and selector libraries compare props or state by reference at the first level. With immutable updates, a change at any depth creates new objects along the path, so a different reference at the top means something changed, and the same reference means nothing did. Cost is O(keys) and does not depend on data size. Deep equality is O(size of data), can run on every render, and has hard cases: circular references, Date, Map, Set, class instances, functions, and getters.
Traps:
- Inline objects, arrays, and functions in props are new references each render, so shallow comparison always fails. Memoize them with
useMemooruseCallback, or move them out of the component. - Mutating state keeps the same reference, so shallow equality reports no change and the UI does not update.
- Arrays need the same rule: same length and same items by
Object.is. - Key order does not matter for objects.
- Prototype and non-enumerable properties are ignored.
A related tool is memoizing the last call: remember the previous arguments and result, and return the result if all arguments are shallow equal. It is cheap and avoids unbounded caches.
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.hasOwn(b, key) && Object.is(a[key], b[key]));
}
function memoizeLast(fn, isEqual = shallowEqual) {
let lastArgs = null;
let lastResult;
let calls = 0;
const memoized = (...args) => {
if (lastArgs && lastArgs.length === args.length && args.every((arg, i) => isEqual(arg, lastArgs[i]))) {
return lastResult;
}
calls++;
lastArgs = args;
lastResult = fn(...args);
return lastResult;
};
memoized.calls = () => calls;
return memoized;
}
const inner = { city: 'Pune' };
console.log('same values:', shallowEqual({ a: 1, b: inner }, { b: inner, a: 1 }));
console.log('nested copy is different:', shallowEqual({ a: 1, b: { city: 'Pune' } }, { a: 1, b: { city: 'Pune' } }));
console.log('NaN:', shallowEqual({ x: NaN }, { x: NaN }), '| +0 and -0:', shallowEqual({ x: 0 }, { x: -0 }));
console.log('undefined vs missing:', shallowEqual({ a: undefined }, { b: undefined }), shallowEqual({ a: 1 }, { a: 1, b: undefined }));
console.log('arrays:', shallowEqual([1, 2, 3], [1, 2, 3]), shallowEqual([1, 2], [1, 2, 3]));
console.log('primitives and null:', shallowEqual(1, 1), shallowEqual(null, {}), shallowEqual(null, null));
let state = { user: { name: 'Asha' }, theme: 'dark' };
const mutated = state;
mutated.theme = 'light';
console.log('mutation looks unchanged:', shallowEqual(state, mutated));
const updated = { ...state, user: { ...state.user, name: 'Ben' } };
console.log('immutable update detected:', !shallowEqual(state, updated), '| untouched branch kept:', updated.theme === state.theme);
const render = memoizeLast((props) => `Hello ${props.name}`);
render({ name: 'Asha' });
render({ name: 'Asha' });
render({ name: 'Ben' });
console.log('calls with equal props reuse the result, total real calls:', render.calls());
const handlerA = () => {};
console.log('inline functions defeat it:', shallowEqual({ onClick: () => {} }, { onClick: () => {} }), '| stable function:', shallowEqual({ onClick: handlerA }, { onClick: handlerA }));Run with Node.js v24.22.1 as js-182.js; two runs gave identical output. Output: same values: true nested copy is different: false NaN: true | +0 and -0: false undefined vs missing: false false arrays: true false primitives and null: true false true mutation looks unchanged: true immutable update detected: true | untouched branch kept: true calls with equal props reuse the result, total real calls: 2 inline functions defeat it: false | stable function: true
Key points
- Compare own keys and Object.is of each value; do not recurse.
- Use Object.hasOwn so undefined values are not confused with missing keys.
- Works with immutable updates: a changed nested value changes the references above it.
- Inline objects and functions defeat shallow comparison; mutation hides changes from it.
- Deep equality is costlier and has edge cases such as cycles and special objects.
Common mistakes
- Mutating state and expecting a change to be detected.
- Creating new object or function props on every render and wondering why memo does nothing.
- Treating a missing key and a key set to undefined as the same.
- Reaching for deep equality when immutable updates and shallow checks would be cheaper.
Follow-ups
- When is deep equality the right choice?
- How does useMemo relate to shallow comparison of dependencies?
- How would you compare two Maps or Sets?
Tips
- Say what the check includes and what it skips.
- Link it to immutable updates; it only works with them.
- Name inline props as the usual reason that memo fails.