'전체 글'에 해당되는 글 78건

React의 Memo는 어떻게 구현되어 있을까?

 

한번 상상해보자. 많이 부족한 코드이지만 아래와 같은 형태가 아닐까?

 

function CreateCahceOperation(pureFunction){
    let cache = {};

    this.operate = function(param){
        if(cache[param]){
            console.log("캐시 된 값 사용");
            return cache[param]
        }

        // 연산 수행
        console.log("한 번도 연산해보지 않은 경우");
        const result = pureFunction(param);
        
        // 캐시
        cache[param] = result;

        return cache[param];
    }
}

const cachedSomeOperation = new CreateCahceOperation(n=>5+n);

cachedSomeOperation.operate(1)

cachedSomeOperation.operate(2)
cachedSomeOperation.operate(2)

cachedSomeOperation.operate(3)
cachedSomeOperation.operate(3)
cachedSomeOperation.operate(3)

cachedSomeOperation.operate(4)
cachedSomeOperation.operate(4)
cachedSomeOperation.operate(4)
cachedSomeOperation.operate(4)

 

연산 가능한 값은 무한하므로 메모리 부족 현상을 대비하는 코드가 필요하다.

캐시 된 값 중 자주 사용 되지 않는 경우 없애는 코드를 추가하여 대비한다.

delete 연산자를 이용하여  cache 객체의 프로퍼티를 제거한다.

캐시 가능한 프로퍼티 수를 정하는 방법도 있다.

 

이제 Github에 있는 React.memo의 구현체를 보자.

 

github.com/facebook/react/blob/9198a5cec0936a21a5ba194a22fcbac03eba5d1d/packages/react/src/ReactMemo.js

 

facebook/react

A declarative, efficient, and flexible JavaScript library for building user interfaces. - facebook/react

github.com

Fuck!

블로그 이미지

_김은찬

두번 다시는 꺾이지 않으리

,