DEV Community

Kenneth Lum
Kenneth Lum

Posted on • Updated on

Why ReactJS using for comparison is better than using `===`

ReactJS uses to compare the hooks' dependency array, instead of using ===. It actually is a better choice. First of all, this post stated how 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:

       [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 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.


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)