memo
자식 Component가 재렌더링하기 부담스러운 상황이 있을 수 있는데, 이 때 memo hook을 사용하면 불필요한 재렌더링을 막을 수 있다. (https://react.dev/reference/react/memo)
import {memo, useState} from 'react'
// 기존 component 정의
//function ChildComponent() {
// return(
// <div>Content</div>
// )
//}
// memo hook을 사용한 component 정의
let ChildComponent = memo(function() {
return <div>Content</div>
})
function ParentComponent() {
let [count, setCount] = useState(0)
return (
<Child/>
{/* state 변경시 부모 component의 state가 변경될 때 자식 component도 재렌더링 됨 */}
{/* memo로 정의된 component는 해당 component로 전달되는 props가 변경될 때에만 재렌더링 됨 */}
<button onClick={() => {setCount(count+1)}}> + </button>
)
}
memo를 사용할 때 주의할 점은 props가 변경될 때 재렌더링하기 때문에 재렌더링 여부를 결정하기 전에 props의 전후를 항상 비교하게 된다. 따라서 props 전후를 비교하는 cost가 너무 큰 경우 또다른 성능문제가 야기될 수 있다.
useMemo
Component 로드시 특정 상황 단 1회만 실행하고 싶은 코드가 있을 경우 사용할 수 있는 hook. (https://react.dev/reference/react/useMemo)
useEffect와 유사한데, useEffect는 return 문장의 HTML요소를 모두 렌더링 한 후 실행되는 반면 useMemo는 렌더링 중에 실행된다는 차이가 있다.
'개발 > React 학습' 카테고리의 다른 글
Lazy Import (0) | 2023.04.27 |
---|---|
Redux 적용 (0) | 2023.04.25 |
Redux 설치 (0) | 2023.04.21 |
Context API (0) | 2023.04.21 |
Transition (0) | 2023.04.20 |