Perfomance Hooks 로 성능 최적화를 위해 불필요한 작업을 건너뛰는 것이다.
비용이 많이 드는 계산 결과를 캐시 가능하다.
🤓 기본 문법
useMemo(calculateValue, dependencies)
calculateValue : 캐싱하려는 값을 계산하는 순수 함수
dependencies : 코드 내 참조된 값
✅ 기본 예제
import { useMemo, useEffect, useState } from "react";
export default function App() {
const [number, setNumber] = useState(0);
const [isKorea, setIsKorea] = useState(true);
const location = { country: isKorea ? "한국" : "일본" };
useEffect(() => {
console.log("useEffect... 호출");
// 오래 걸리는 작업
}, [location]);
return (
<header className="App-header">
<h2>Count</h2>
<input
type="number"
value={number}
onChange={(e) => setNumber(e.target.value)}
/>
<hr />
<h2>어느 나라에 있어요?</h2>
<p>나라: {location.country}</p>
<button onClick={() => setIsKorea(!isKorea)}>Update</button>
</header>
);
}
객체는 값이 저장될 때 메모리 주소값이 변경 되기 때문에 useEffect가 location이 변경되었다고 인식하고 useEffect가 실행된다.
⭐ useMemo를 활용해서 문제를 해결 할 수 있다.
-> isKorea의 값이 변경되었을 때만 location 의 객체를 다시 만들어 주도록 수정한다.
// const location = { country: isKorea ? "한국" : "일본" }; 을 아래와 같이 수정하면 된다.
const location = useMemo(() => {
return {
country: isKorea ? "한국" : "일본",
};
}, [isKorea]);