const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
자바스크립트에서는 원시타입과 객체타입이 있다.
원시타입?
어떤 변수에 원시타입의 값을 할당하면 그 값은 박스에 바로 들어간다.
같은 원시값을 가지고 있는 두가지 변수를 비교하면 true가 나온다.
객체타입?
하지만 객체는 어떤 변수에 객체타입의 값을 할당하면 객체는 크기가 크기 때문에 메모리상에 값이 할당되어 보관되고 변수안에는 그 객체에 담긴 메모리의 주소가 할당이 된다.
똑같은 객체를 넣어준 변수를 비교하면 false가 나온다. 변수라는 상자안에는 메모리 상의 주소가 들어가 있기 때문에 다른 주소에 저장되어 있기 때문이다.
오브젝트가 똑같아 보여도 다른 오브젝트이다. 렌더링 될 때마다 다른 이전과 객체와 메모리상 공간에 저장된다. 그리고 변수는 또다른 객체의 주소를 참조하게 된다.
따라서 똑같이 생긴 오브젝트여도 변경이 되기 때문에 코드를 실행해도 계속 호출이 된다.
fuction App(){
const [number , setNumber ] = useState(0);
const [isKorea, setIsKorea] = useState(true);
const location = {
contry : isKorea ? '한국' : '외국'
}
useEffect(()=>{
console.log('useEffect호출')
},[location])
return(
<input onChange={(e)=>{setNumber(e.target.value}}/>
<button onclick={)=>setIsKorea(!Korea)}></button>
)
}
이를 해결해 주기 위해서는 app 컴포넌트가 렌더링이 되었을때 location 변수가 초기화 되는 것을 막아줘야한다. location변수는 iskorea가 state가 바꼈을때만 초기화 되게 할것이다.
fuction App(){
const [isKorea, setIsKorea] = useState(true);
const [isKorea, setIsKorea] = useState(true);
const location = useMemo(()=>{
return {
contry : isKorea ? '한국' : '외국'
}
},[isKorea])
useEffect(()=>{
console.log('useEffect호출')
},[location])
return(
<input onChange={(e)=>{setNumber(e.target.value}}/>
<button onclick={)=>setIsKorea(!Korea)}></button>
)
}
'Front-end > React' 카테고리의 다른 글
styled-components (0) | 2022.03.14 |
---|---|
[React] useCallback (0) | 2022.03.09 |
Redux 란 ? Redux Setting Up - 1 (0) | 2022.03.07 |
[React] Image Gallery 라이브러리 사용하기 (0) | 2022.02.23 |
[React] Dropzone 라이브러리 사용하기 (0) | 2022.02.19 |