
- 컴포넌트 렌더링 최적화
- useCallback
- useMemo
무분별한 컴포넌트의 렌더링을 방지하며 필요한 경우에만 컴포넌트가 렌더링될 수 있도록 하는 것
의도하지 않은 곳에서 재 렌더링이 발생한 경우를 다음과 같이 표현 import { useState } from "react";
import Box from "./component/Box";
function App() {
const [size, setSizes] = useState(100);
const [isDark, setIsDark] = useState(false);
const createBoxStyle = () => {
return {
backgroundColor: "pink",
width: `${size}px`,
height: `${size}px`,
};
};
return (
<div style={{ background: isDark ? "black" : "white" }}>
<input
type="number"
value={size}
onChange={(e) => {
setSizes(+e.currentTarget.value);
}}
/>
<button
onClick={() => {
setIsDark(!isDark);
}}
>
Change Theme
</button>
<Box createBoxStyle={createBoxStyle} />
</div>
);
}
export default App;
import { useEffect, useState } from "react";
type CreateBoxStyle = {
backgroundColor: string;
width: string;
height: string;
};
interface BoxProps {
createBoxStyle: () => CreateBoxStyle;
}
function Box({ createBoxStyle }: BoxProps) {
const [style, setStyle] = useState({} as CreateBoxStyle);
useEffect(() => {
console.log("박스 사이즈 조절");
setStyle(createBoxStyle());
}, [createBoxStyle]);
return <div style={style}></div>;
}
export default Box;




- change theme를 누르면 onClick 이벤트를 통해 setState 실행
- setState 함수로 state를 변경하면 컴포넌트 재 렌더링을 발생
- 재 렌더링이 발생하게 되면 컴포넌트(예시에선 app 컴포넌트)가 초기화
- 컴포넌트가 초기화되게 되면 createBoxStyle은 결국 js 함수이기 때문에 참조값(주소)가 변경되게 되고 변경된 참조값의 createBoxStyle이 prop으로 전달
- useEffect는 변수의 값이 달라졌다 생각하여 내부 코드를 실행
참조하는 주소가 달라지기 때문에 재 렌더링 발생React Hook에서 제공하는
useMemo, useCallback사용

콜백 함수 자체를 메모리에 넣어 필요할 때마다 사용하도록 돕는 hookMemoization 하여 컴포넌트 렌더링 최적화
맨 처음 값을 계산할때 해당 값을 메모리에 저장하여 캐싱 후 그 값이 필요할 때마다 캐시에서 가져와서 사용const createBoxStyle = useCallback(() => {
return {
backgroundColor: "pink",
width: `${size}px`,
height: `${size}px`,
};
}, [size]);




Memoization 하여 컴포넌트 렌더링 최적화 const createBoxStyle = {
backgroundColor: "pink",
width: `${size}px`,
height: `${size}px`,
};
import { useEffect, useState } from "react";
type CreateBoxStyle = {
backgroundColor: string;
width: string;
height: string;
};
interface BoxProps {
createBoxStyle: CreateBoxStyle;
}
function Box({ createBoxStyle }: BoxProps) {
const [style, setStyle] = useState({} as CreateBoxStyle);
useEffect(() => {
console.log("박스 사이즈 조절");
setStyle(createBoxStyle);
}, [createBoxStyle]);
return <div style={style}></div>;
}
export default Box;
const createBoxStyle = useMemo(() => {
return {
backgroundColor: "pink",
width: `${size}px`,
height: `${size}px`,
};
}, [size]);


별 코딩님 - React Hooks에 취한다 - useMemo 제대로 사용하기 | 리액트 훅스 시리즈
https://www.youtube.com/watch?v=e-CnI8Q5RY4&t=761s
별 코딩님- React Hooks에 취한다 - useCallback 제대로 사용하기 | 리액트 훅스 시리즈