리액트에서 메모이제이션을 어떤 방식으로 하는지?
리액트에서 메모이제이션을 사용하는 방법
리액트에서 메모이제이션(Memoization)은 성능 최적화에 중요한 역할을 합니다. 메모이제이션은 동일한 입력에 대해 이전에 계산된 결과를 저장해두고, 동일한 입력이 다시 들어오면 저장된 결과를 재사용하는 기법입니다. 리액트에서는 이 개념을 React.memo, useMemo, useCallback과 같은 훅을 통해 활용할 수 있습니다.
React.memo를 사용한 컴포넌트 메모이제이션
React.memo는 고차 컴포넌트(HOC, Higher Order Component)로, 컴포넌트를 메모이제이션하여 불필요한 리렌더링을 방지합니다. 이를 통해 성능을 최적화할 수 있습니다. 예를 들어, 부모 컴포넌트가 리렌더링되어도 React.memo로 감싼 자식 컴포넌트는 prop이 변경되지 않는 한 리렌더링되지 않습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import React from "react";
// 자식 컴포넌트
const ChildComponent = ({ value }) => {
console.log("ChildComponent 렌더링");
return <div>{value}</div>;
};
// 메모이제이션된 자식 컴포넌트
const MemoizedChildComponent = React.memo(ChildComponent);
// 부모 컴포넌트
const ParentComponent = () => {
const [count, setCount] = React.useState(0);
const [value, setValue] = React.useState("Hello");
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment</button>
<MemoizedChildComponent value={value} />
</div>
);
};
export default ParentComponent;
위 예제에서 ParentComponent의 상태가 변경될 때마다 MemoizedChildComponent는 리렌더링되지 않으며, value prop이 변경될 때만 리렌더링됩니다.
useMemo를 사용한 값 메모이제이션
useMemo는 함수의 결과 값을 메모이제이션하여 성능을 최적화합니다. 이는 계산 비용이 높은 작업이나 반복되는 작업을 최적화하는 데 유용합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import React from "react";
const ExpensiveComponent = ({ number }) => {
const computeFactorial = (n) => {
console.log("컴퓨팅 팩토리얼");
if (n === 0) return 1;
return n * computeFactorial(n - 1);
};
// useMemo를 사용하여 값 메모이제이션
const factorial = React.useMemo(() => computeFactorial(number), [number]);
return (
<div>
Factorial of {number} is {factorial}
</div>
);
};
const ParentComponent = () => {
const [count, setCount] = React.useState(0);
const [number, setNumber] = React.useState(5);
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment</button>
<ExpensiveComponent number={number} />
</div>
);
};
export default ParentComponent;
위 예제에서 number가 변경될 때만 computeFactorial 함수가 호출되며, 그렇지 않으면 메모이제이션된 값을 재사용합니다.
useCallback을 사용한 함수 메모이제이션
useCallback은 함수를 메모이제이션하여, 불필요한 함수 재생성을 방지합니다. 이는 자식 컴포넌트에 콜백 함수를 전달할 때 유용합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React from "react";
const ChildComponent = React.memo(({ onClick }) => {
console.log("ChildComponent 렌더링");
return <button onClick={onClick}>Click me</button>;
});
const ParentComponent = () => {
const [count, setCount] = React.useState(0);
// useCallback을 사용하여 함수 메모이제이션
const handleClick = React.useCallback(() => {
console.log("Button clicked");
}, []);
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment</button>
<ChildComponent onClick={handleClick} />
</div>
);
};
export default ParentComponent;
위 예제에서 handleClick 함수는 useCallback을 통해 메모이제이션되며, ParentComponent가 리렌더링되더라도 동일한 함수 인스턴스가 ChildComponent에 전달됩니다. 따라서 ChildComponent는 불필요한 리렌더링을 피할 수 있습니다.
