Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  132] [ 1]  / answers: 1 / hits: 113896  / 8 Years ago, fri, march 18, 2016, 12:00:00

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.


More From » reactjs

 Answers
35

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.


[#62891] Wednesday, March 16, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
karivictoriab

Total Points: 530
Total Questions: 90
Total Answers: 95

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;