Skip to content

Commit

Permalink
✅ 백광인 2024-03-04
Browse files Browse the repository at this point in the history
  • Loading branch information
RookieAND committed Mar 5, 2024
1 parent 1ed5a8f commit 0ba5d65
Showing 1 changed file with 48 additions and 1 deletion.
49 changes: 48 additions & 1 deletion docs/RookieAND/dil/2024-03-04.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
- 기본적으로 React 에서는 `Object.is` 메서드로 두 값의 동등 비교를 시행하며, 참조형 타입의 경우 같은 메모리 주소를 참조한다면 같다고 판단한다.
- 이렇게 두 객체의 내부 데이터를 상세히 조회하지 않고 참조된 메모리 주소만을 판별하는 동등 비교 방식이 **"얕은 비교"** 이다.

### ️ JS 의 데이터 타입
# ️ JS 의 데이터 타입

- JS 의 데이터 타입은 크게 원시 타입과 객체 타입으로 나뉜다.

Expand Down Expand Up @@ -70,3 +70,50 @@ function is(a, b) {
2. `x !== x && y !== y` 인 경우
- 엄격한 비교의 경우 `x !== x` 를 성립하는 조건은 x 가 NaN 인 경우 외에 없다.
- 따라서 `x``y` 가 둘 다 NaN 일 경우 true 를 반환하고, 그 외에는 false 를 반환한다.

### ✏️ ShallowEqual in React

- React 에서는 동등 비교가 필요한 경우 `Object.is` 에 더해 별도의 추가 작업을 더하여 정의한 shallowEqual 유틸 함수를 사용한다.
- shallowEqual 의 경우 object 를 비교할 때 1 Depth 만 체크하므로 복잡한 구조의 Object 를 Props 로 넘길 경우 메모이제이션이 정상적으로 동작하지 않는다.

- Source : https://github.com/facebook/react/blob/master/packages/shared/shallowEqual.js

```js
function shallowEqual(objA: mixed, objB: mixed): boolean {
if (is(objA, objB)) {
return true;
}

if (
typeof objA !== 'object' ||
objA === null ||
typeof objB !== 'object' ||
objB === null
) {
return false;
}

const keysA = Object.keys(objA);
const keysB = Object.keys(objB);

if (keysA.length !== keysB.length) {
return false;
}

// Test for A's keys different from B.
for (let i = 0; i < keysA.length; i++) {
if (
!hasOwnProperty.call(objB, keysA[i]) ||
!is(objA[keysA[i]], objB[keysA[i]])
) {
return false;
}
}

return true;
}
```

- 가장 먼저 `Object.is` 를 사용하여 두 값이 동등한지를 체크한다.
- 이후 a 와 b 가 object 가 아닌 경우 (null 제외) 에는 전부 false 를 반환한다.
- 만약 a 와 b 가 object 라면, a 가 가진 키가 b 에도 있으며 두 value 가 같은지를 비교한다. (1 Depth 만 비교)

0 comments on commit 0ba5d65

Please sign in to comment.