import { type FunctionComponent } from "react";
import { shallowEquals } from "../equals";
import { useRef } from "../hooks";
export function memo<P extends object>(Component: FunctionComponent<P>, equals = shallowEquals) {
// 새로운 컴포넌트 정의, 렌더링 할 때 props 넘겨줌.
const memoizatedComponent: FunctionComponent<P> = (props) => {
const cache = useRef<{ preProps: P; result: React.ReactElement } | null>(null);
// 최초 렌더링 또는 props 변경 시 컴포넌트 호출하여 렌더링 값 설정
if (cache.current === null || !equals(cache.current.preProps, props)) {
const newResult = Component(props);
cache.current = { preProps: props, result: newResult };
}
return cache.current.result;
};
return memoizatedComponent;
}

const cache = useRef<{ preProps: P; result: React.ReactElement } | null>(null);
...
if (cache.current === null || !equals(cache.current.preProps, props)) {
const newResult = Component(props);
cache.current = { preProps: props, result: newResult };
}
prevProps: P:💡 P는 "아직 정해지지 않은, 어떤 객체 타입"을 나타내는 자리표시자(placeholder)
result: React.ReactElement:<div>Hello</div>)이며, 이는 React 내부적으로 React.ReactElement 타입으로 표현됩니다.| null:
Component(props)를 호출하여 렌더링한 값을 result에 넣는 이유:
메모이제이션(Memoization) 의 핵심