DEV Community

Kenneth Lum
Kenneth Lum

Posted on • Updated on

Why ReactJS using Object.is() for comparison is better than using `===`

ReactJS uses Object.is() to compare the hooks' dependency array, instead of using ===. It actually is a better choice. First of all, this post stated how Object.is() is different from ===.

Why is it better? It is because:

  1. If we did something for the dependency array [1, 2, NaN], and the next time, it is [1, 2, NaN] again, then === would have indicated them different, because NaN !== NaN in JavaScript. (it is the only value that is not === to itself in JavaScript). Example:

    https://stackblitz.com/edit/react-yxngvv?file=index.js

       [1, 2, NaN]
    

    is considered to be the same the next time useEffect() or useMemo() sees it. They are both called twice only in the example: the first time, and when the array changed from [1, 2, NaN] to [1, 3, NaN].

  2. On the other hand, for the dependency array [1, 2, 0], if the next time, the dependency array is [1, 2, -0], ReactJS would actually consider them to be different, due to Object.is() indicating 0 and -0 are different. In a website built by NASA, or even by college students, 0 and -0 actually may give different results for computations.

Example:

https://stackblitz.com/edit/react-djex2r?file=index.js

The console log shows that the function inside of useEffect() and useMemo() are called every time. You can also actually see the output of the component showing a result alternating between Infinity and -Infinity. ReactJS is actually on a "safer side", in which ReactJS will do something again, when 0 becomes -0, because the results could be different, and it won't be desirable when the screen should display -Infinity but it keeps the Infinity unchanged on screen.

Top comments (0)