-
[React] useCallback VS React.Memo VS useEffect프로그래밍/React 2023. 7. 3. 17:02
지극히 개인적인 사견임을 밝힙니다. 아닌부분은 공부할수록 바뀔 수 있습니다.
먼저 이 Hooks가 사용되는 경우는 최적화라고 보고 있다.
React.Momo의 경우 component가 export 될때 또는 함수 자체에 덮어씌듯이 씌어놓으면 부모컴포넌트의 리랜더링에도 부모가 내려주는 props가 변하지 않는다면 랜더링되지 않아서 내가(자식컴포넌트) 가진 함수 및 기타 data들이 리랜더링되지 않아 메모이제이션 과정에서 차지하는 메모리를 제외하고는 cost가 없다는게 가장 큰 장점이다.
useCallback의 경우 첫번째 인자로는 callback 함수 두번째 인자는 배열로 deps라고도 불리고 deps의 변경에만 반응하여 함수를 다시 생성을 한다(리랜더링시에) 그렇기에 deps의 변화가 없다면 내가 리랜더링을 하더라도 useCallback은 다시 만들어지지 않는다.
useEffect의 경우 인자는 useCallback과 동일하며 마찬가지로 리랜더링시에 deps의 변화에만 반응하여 다시생성된다.
랜더링될때 순서를 앞선 유투브 자료를 통해서 알아보면
함수안에서 그냥 console.log("render입니다")를 찍고 useEffect(()=>console.log("Effect입니다"), []) useEffect를 사용한 경우를 알아보면 랜더링이 먼저 일어나고 마운트가 일어나는데 이 마운트 때 useEffect가 실행이 된다 그래서 랜더링과정인 자식컴포넌트에게 전달해주는 과정을 마치고나서 useEffect가 일어나는 모습을 보인다
나는 useEffect가 제일먼저 일어나는줄 알았다.
또 useEffect에 들어가는 return(클린업) 얘는 언마운트 될때 실행이 된다고 한다.
'프로그래밍 > React' 카테고리의 다른 글
[React] ReactQuery에 대해서 좀 더 알아보자 (0) 2023.07.12 [React] Portal 사용해서 Modal 만들어보기 (0) 2023.07.11 [리액트 알쓸신잡] Hook - 1 - useMemo VS useCallback (0) 2023.06.22 [리액트 다루는 기술] 리덕스 작동원리 && 기초 (0) 2023.06.21 [리액트를 다루는 기술] immer (0) 2023.06.20