Why and how does Object.assign increase app performance in React?

Question

I am reading the Facebook tutorial for React. About 40% of the way through, there's a section called Why Immutability is Important where they state (regarding the importance of immutability):

The end result is the same but by not mutating (or changing the underlying data) directly we now have an added benefit that can help us increase component and overall application performance.

My question is: why/how? That is, in React, specifically why/how does immutability (using Object.assign(...), etc.) "help increase...overall application performance"?


Show source
| javascript   | reactjs   | performance   | immutability   2017-01-03 13:01 2 Answers

Answers ( 2 )

  1. 2017-01-03 13:01

    I think that it is easier to understand with arrays:

    Imagine that you have an array, containing many, many entries. You replace one entry with another - to see if anything changed react has to loop through the whole array.

    Now, imagine that everytime you make some changes you create new array - then the only thing react has to do is to compare references

    Object.assign does the same - instead of changing existing object, you create a new one, so that react can detect changes simply by comparing references

  2. 2017-01-03 14:01

    In React, state changes do not have to rely upon the differences in individual value changes within an object, it is sufficient to know if the state has changed at all.

    For non-primitive data types like arrays and objects, one can check for equality by checking to see if they refer to or reference the same structure.

    Using Object.assign or spread syntax creates a new copy of an object and therefore a new reference. Since the copy now points to a new reference, the intent to change the structure can be inferred by doing a reference equality check.

    Caveat: - Since equality is being checked by reference and not by value, React will treat a state updated with Object.assign as being updated even if there were no changes to the nested values.

◀ Go back