How does shallow compare work in react

JavascriptReactjs

Javascript Problem Overview


In this documentation of React, it is said that

> shallowCompare performs a shallow equality check on the current props and nextProps objects as well as the current state and nextState objects.

The thing which I am unable to understand is If It shallowly compares the objects then shouldComponentUpdate method will always return true, as

> We should not mutate the states.

and if we are not mutating the states then the comparison will always return false and so the shouldComponent update will always return true. I am confused about how it is working and how will we override this to boost the performance.

Javascript Solutions


Solution 1 - Javascript

Shallow compare does check for equality. When comparing scalar values (numbers, strings) it compares their values. When comparing objects, it does not compare their attributes - only their references are compared (e.g. "do they point to same object?").

Let's consider the following shape of user object

user = {
  name: "John",
  surname: "Doe"
}

Example 1:

const user = this.state.user;
user.name = "Jane";

console.log(user === this.state.user); // true

Notice you changed users name. Even with this change, the objects are equal. The references are exactly the same.

Example 2:

const user = clone(this.state.user);
console.log(user === this.state.user); // false

Now, without any changes to object properties they are completely different. By cloning the original object, you create a new copy with a different reference.

Clone function might look like this (ES6 syntax)

const clone = obj => Object.assign({}, ...obj);

Shallow compare is an efficient way to detect changes. It expects you don't mutate data.

Solution 2 - Javascript

shallow comparison is when the properties of the objects being compared is done using "===" or strict equality and will not conduct comparisons deeper into the properties. for e.g.

// a simple implementation of the shallowCompare.
// only compares the first level properties and hence shallow.
// state updates(theoretically) if this function returns true.
function shallowCompare(newObj, prevObj){
    for (key in newObj){
        if(newObj[key] !== prevObj[key]) return true;
    }
    return false;
}
// 
var game_item = {
    game: "football",
    first_world_cup: "1930",
    teams: {
         North_America: 1,
         South_America: 4,
         Europe: 8 
    }
}
// Case 1:
// if this be the object passed to setState
var updated_game_item1 = {
    game: "football",
    first_world_cup: "1930",
    teams: {
         North_America: 1,
         South_America: 4,
         Europe: 8 
    }
}
shallowCompare(updated_game_item1, game_item); // true - meaning the state
                                               // will update.

Although both the objects appear to be same, game_item.teams is not the same reference as updated_game_item.teams. For 2 objects to be same, they should point to the same object. Thus this results in the state being evaluated to be updated

// Case 2:
// if this be the object passed to setState
var updated_game_item2 = {
    game: "football",
    first_world_cup: "1930",
    teams: game_item.teams
}
shallowCompare(updated_game_item2, game_item); // false - meaning the state
                                               // will not update.

This time every one of the properties return true for the strict comparison as the teams property in the new and old object point to the same object.

// Case 3:
// if this be the object passed to setState
var updated_game_item3 = {
    first_world_cup: 1930
}
shallowCompare(updated_game_item3, game_item); // true - will update

The updated_game_item3.first_world_cup property fails the strict evaluation as 1930 is a number while game_item.first_world_cup is a string. Had the comparison been loose (==) this would have passed. Nonetheless this will also result in state update.

Additional Notes:

  1. Doing deep compare is pointless as it would significantly effect performance if the state object is deeply nested. But if its not too nested and you still need a deep compare, implement it in shouldComponentUpdate and check if that suffices.

  2. You can definitely mutate the state object directly but the state of the components would not be affected, since its in the setState method flow that react implements the component update cycle hooks. If you update the state object directly to deliberately avoid the component life-cycle hooks, then probably you should be using a simple variable or object to store the data and not the state object.

Solution 3 - Javascript

> Shallow compare works by checking if two values are equal in case of primitive types like string, numbers and in case of object it just checks the reference. So if you shallow compare a deep nested object it will just check the reference not the values inside that object.

Solution 4 - Javascript

There is also legacy explanation of shallow compare in React:

> shallowCompare performs a shallow equality check on the current props and nextProps objects as well as the current state and nextState objects. > > It does this by iterating on the keys of the objects being compared and returning true when the values of a key in each object are not strictly equal.

UPD: Current documentation says about shallow compare:

> If your React component's render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases. > >React.PureComponent's shouldComponentUpdate() only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences. Only extend PureComponent when you expect to have simple props and state, or use forceUpdate() when you know deep data structures have changed

UPD2: I think Reconciliation is also important theme for shallow compare understanding.

Solution 5 - Javascript

The shallow equal snippet by @supi above (https://stackoverflow.com/a/51343585/800608) fails if prevObj has a key that newObj doesn't have. Here is an implementation that should take that into account:

const shallowEqual = (objA, objB) => {
  if (!objA || !objB) {
    return objA === objB
  }
  return !Boolean(
    Object
      .keys(Object.assign({}, objA, objB))
      .find((key) => objA[key] !== objB[key])
  )
}

Note that the above doesn't work in Explorer without polyfills.

Solution 6 - Javascript

The accepted answer can be a bit misleading for some people.

user = {
  name: "John",
  surname: "Doe"
}

const user = this.state.user;
user.name = "Jane";

console.log(user === this.state.user); // true

This statement in particular "Notice you changed users name. Even with this change objects are equal. They references are exactly same."

When you do the following with objects in javascript:

const a = {name: "John"};
const b = a;

Mutating any of the two variables will change both of them because they have the same reference. That's why they will always be equal (==, ===, Object.is()) to each other.

Now for React, the following is the shallow comparison function: https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/shallowEqual.js

/**
 * Performs equality by iterating through keys on an object and returning false
 * when any key has values which are not strictly equal between the arguments.
 * Returns true when the values of all keys are strictly equal.
 */
function shallowEqual(objA: mixed, objB: mixed): boolean {
  if (is(objA, objB)) {
    return true;
  }

  if (typeof objA !== 'object' || objA === null ||
      typeof objB !== 'object' || objB === null) {
    return false;
  }

  const keysA = Object.keys(objA);
  const keysB = Object.keys(objB);

  if (keysA.length !== keysB.length) {
    return false;
  }

  // Test for A's keys different from B.
  for (let i = 0; i < keysA.length; i++) {
    if (
      !hasOwnProperty.call(objB, keysA[i]) ||
      !is(objA[keysA[i]], objB[keysA[i]])
    ) {
      return false;
    }
  }

  return

For non-primitives (Objects), it checks:

  1. If the first object is equal (using Object.is()) to the second.
  2. If not, it checks if each key-value pair in the first object is equal (using Object.is()) to that of the second. This is done for the first level of keys. If the object has a key whose value is another object, this function does not check for equality further down the depth of the object.

Solution 7 - Javascript

There is an implementation with examples.

const isObject = value => typeof value === 'object' && value !== null;

const compareObjects = (A, B) => {
  const keysA = Object.keys(A);
  const keysB = Object.keys(B);
 
  if (keysA.length !== keysB.length) {
    return false;
  }
 
  return !keysA.some(key => !B.hasOwnProperty(key) || A[key] !== B[key]);
};

const shallowEqual = (A, B) => {
  if (A === B) {
    return true;
  }
 
  if ([A, B].every(Number.isNaN)) {
    return true;
  }
  
  if (![A, B].every(isObject)) {
    return false;
  }
  
  return compareObjects(A, B);
};

const a = { field: 1 };
const b = { field: 2 };
const c = { field: { field: 1 } };
const d = { field: { field: 1 } };

console.log(shallowEqual(1, 1)); // true
console.log(shallowEqual(1, 2)); // false
console.log(shallowEqual(null, null)); // true
console.log(shallowEqual(NaN, NaN)); // true
console.log(shallowEqual([], [])); // true
console.log(shallowEqual([1], [2])); // false
console.log(shallowEqual({}, {})); // true
console.log(shallowEqual({}, a)); // false
console.log(shallowEqual(a, b)); // false
console.log(shallowEqual(a, c)); // false
console.log(shallowEqual(c, d)); // false

Solution 8 - Javascript

Very simple to understand it. first need to understand the pure component and regular component, if a component has coming props or state is changing then it will re-rendered the component again. if not then not. in regular component shouldComponentUpdate by default true. and in pure component only the time when state change with diff value.

so now what is shallow component or shallow ? lets take an simple example. let a = [1,2,3], let b = [1,2,3],

a == b ==> shallow take it false, a == c ==> shallow take it true. c has any diff value.

now i think you can understand it. the diff in both regular and pure component with shallow component if you like it, also do like share and subscribe my youtube channel https://www.youtube.com/muosigmaclasses

Thanks.

Solution 9 - Javascript

I feel that none of the answers actually addressed the crucial part in your question, the answers merely explain what shallow comparison is (whether they mean the JavaScript default shallow comparison that is a result of the === or == operator or React's shallowCompare() function)

To answer your question, my understanding so far of React makes me believe that yes indeed by not directly mutating the states then shouldComponentUpdate will always return true thus always causing a re-render no matter what objects we pass in setState even if the objects passed to setState hold the same values stored in the current state

example:

Say I have a React.Component with the current state and function:

this.state = {data: {num: 1}} // current state object
    
foo() { // something will cause this function to called, thus calling setState
       this.setState( {data: {num: 1}} ); // new state object
}

You can see that setState passed the same object (value-wise) however plain React is not smart enough to realize that this component shouldn't update/re-render.

To overcome this, you have to implement your version of shouldComponentUpdate in which you apply deep comparison yourself on the state/props elements that you think should be taken into consideration.

Check out this article on lucybain.com that briefly answers this question.

Solution 10 - Javascript

It took me a while to actually know shallow compare and === are two different thing, especially while reading redux documentation in the following.

> However, when an action is dispatched to the Redux store, useSelector() only forces a re-render if the selector result appears to be different than the last result. As of v7.1.0-alpha.5, the default comparison is a strict === reference comparison. This is different than connect(), which uses shallow equality checks on the results of mapState calls to determine if re-rendering is needed. This has several implications on how you should use useSelector().

strict equal

so step by step, the strict equal === is very consistently defined by the Javascript language, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality

What it does is to compare two items by value if they are primitive, and then by reference if they are object. Of course if the types of two objects are different, they will never match.

shallow compare

shallow probably isn't a build-in feature of the language. Couple of the answers here pointed us to some variation of the implementation, https://github.com/facebook/fbjs/blob/main/packages/fbjs/src/core/shallowEqual.js

The idea is to compare two items by value if they are primitive. But for non primitives, we go one level lower. For objects, if the keys are different between two objects, we say they are not same. If the value under a key is different, we say they are not same either.

summary

This means, shallow comparison checks more than the strict equal ===, especially when it comes to the object. A quick look might suggest, === does not do too much guess work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAjay GaurView Question on Stackoverflow
Solution 1 - JavascriptAndreycoView Answer on Stackoverflow
Solution 2 - JavascriptsupiView Answer on Stackoverflow
Solution 3 - Javascriptakhil choudharyView Answer on Stackoverflow
Solution 4 - JavascriptvalexView Answer on Stackoverflow
Solution 5 - JavascriptmzedelerView Answer on Stackoverflow
Solution 6 - JavascriptNishant SalhotraView Answer on Stackoverflow
Solution 7 - JavascriptMax StarlingView Answer on Stackoverflow
Solution 8 - JavascriptMuo sigma classesView Answer on Stackoverflow
Solution 9 - JavascriptA. KhaledView Answer on Stackoverflow
Solution 10 - JavascriptwindmaomaoView Answer on Stackoverflow