ReasonJun

React : Shallow / Deep compare 본문

Frontend/React

React : Shallow / Deep compare

ReasonJun 2023. 6. 13. 14:14
728x90

In React, "shallow compare" and "deep compare" refer to different approaches for comparing the values of props and state to determine if a component should re-render.

  • Shallow Compare: Shallow comparison, which is the default behavior in React, involves comparing the prop and state values by their references. When using shallow comparison, React checks if the references of the current props and state are the same as the references of the previous props and state. If the references are different, React considers the values as changed and triggers a re-render of the component.

Shallow comparison has some important characteristics:

  • It is performed using the Object.is method, which checks for strict equality (===) between two values.
  • It is fast and efficient because it only compares the references of the props and state.
  • If the prop or state values are primitives (e.g., numbers, strings, booleans), shallow comparison compares their values directly.
  • If the prop or state values are objects or arrays, shallow comparison compares the references to those objects or arrays.

 

 

  • Deep Compare: Deep comparison involves comparing the actual values of the props and state, rather than just comparing the references. In a deep comparison, every property and element within the prop or state values are compared recursively to determine if any changes have occurred. This comparison can be performed using utility libraries like Lodash's _isEqual or custom comparison logic.

Deep comparison has the following characteristics:

  • It involves more computational overhead compared to shallow comparison since it examines the values of nested properties and elements.
  • It provides a more fine-grained comparison, allowing for precise detection of changes within complex data structures.
  • It can be useful when working with deeply nested props or state, where shallow comparison may not capture the necessary changes accurately.
  • Deep comparison can be achieved by implementing custom comparison functions or using utility libraries that support deep comparison, like Lodash's _isEqual.

The choice between shallow and deep comparison depends on the specific requirements of your React component and the structure of your props and state. Shallow comparison is the default and often sufficient for most use cases, as it is performant and covers many scenarios. However, in cases where more granular comparison is needed or when dealing with complex nested data, deep comparison can be applied to ensure accurate detection of changes.

 

 

 

 

728x90
Comments