Skip to content
React logic · Core · about 15 minutes

Shallow equal

Implement shallowEqual(a, b), the comparison React.memo uses for props. Two values are equal when Object.is says so, or when both are non-null objects with the same own keys and Object.is-equal values for every key. Nested objects and functions are compared by reference only. Each test names the pair it builds.

Start from

function shallowEqual(a, b) {
  // Compare one level deep, with Object.is for each value.
}

Hints

Each hint gives away a little more. Open one only when you need it.

  1. Hint 1

    Object.is first. Then both must be objects and not null.

  2. Hint 2

    Compare the number of keys, then every key of a: b must own it and hold an Object.is-equal value.

Solution

From here on the page gives the method away. If you are still solving, go back to the hints.

JavaScript
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 keys = Object.keys(a);
  if (keys.length !== Object.keys(b).length) return false;
  return keys.every(
    (key) =>
      Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key]),
  );
}

What an interviewer looks for

It explains why React.memo fails with an inline object or handler: the new prop is a different reference. Being able to write it shows you understand memoization, not only its API.