Shallow Equality vs Deep Equality in Javascript

 In frameworks like React, where performance hinges on detecting whether props or state have changed. That is a reason why equality checks are crucial in software development because they determine when to re-render components, update state, or skip unnecessary computations.

If equality checks are too strict or too loose, it can lead to:

- Unnecessary re-renders

- Missed updates

So in this blog, let's deep dive Shallow equality and Deep equality in Javascript. Let's start!!!

1. What is Shallow Equality?

- Shallow equality means comparing two values or objects by checking whether their top-level properties or references are the same - without diving into nested properties.

- Often use in React (React.memo, PureComponent)

    + React.memo: prevents unnecessary re-renders by shallow comparing props

    + PureComponent: uses shallow equality for props and state in shouldComponentUpdate

2. What is Deep Equality?

- Deep equality compares every level of an object or array - even nested values - to determine if they are structurally and value-wise identical


- Useful for detecting subtle data changes (e.g checking config/state objects deeply)

3. Shallow equality vs Deep equality

- Shallow:

    + Speed: faster 
    + Accuracy: Only check top-level 
    + Use cases: React.memo, PureComponent, prop diffing,...

- Deep:

    + Speed: slower
    + Accuracy: Thorough (nested values) 
    + Use cases: form states, Redux diffs,...

4. When to use Which?

- Shallow:
    + If you care only about top-level changes
    +







Post a Comment

0 Comments