DEV Community

Kenneth Lum
Kenneth Lum

Posted on • Edited on

6

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series