← React Beginner Questions - Set 5 Q48

What is the difference between shallow and deep comparison in React?

React Beginner Questions - Set 5

React's own optimisations are shallow. Deep equality is something you add deliberately, and it is rarely what you want on every render.

Example

// Shallow: one level, Object.is per key
function shallowEqual(a, b) {
  const ka = Object.keys(a), kb = Object.keys(b);
  if (ka.length !== kb.length) return false;
  return ka.every(k => Object.is(a[k], b[k]));
}

shallowEqual({ user: { id: 1 } }, { user: { id: 1 } });  // false (different objects)

// Deep: walks the whole structure
const deepEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
deepEqual({ user: { id: 1 } }, { user: { id: 1 } });      // true

// React.memo and PureComponent use shallowEqual

What to notice

← Back to the question list