PureComponent의 이해

Sohyeon Bak·2021년 3월 1일
0

React

목록 보기
1/9
post-thumbnail

PureComponent란

리액트 공식문서

React.PureComponent
React.PureComponent is similar to React.Component. The difference between them is that React.Component doesn’t implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison.

If your React component’s render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.


먼저, PureComponent를 쓰는 이유는 랜더 최적화를 위해서다. class component를 사용할 때 쓸 수 있으며, 데이터의 변화가 없는 컴포넌트에서 랜더가 되는 것을 방지해준다. 해당하지 않는 컴포넌트에서 PureComponent를 선언하면 불필요한 랜더를 하지 않을 수 있다.

PureComponent는 Component와 유사하지만 다른 점이 있다면 shouldComponentUpdate()를 포함하고 있다. 이전 값과 현재 값을 비교해서 변화가 있을때 true를 실행해서 랜더함수를 실행시킨다. 이때 데이터의 비교를 shallow하게 비교한다고 공식문서에 적혀있다.

'얕은'이라는 뜻을 가진 shallow는 이전 데이터와 현재 데이터를 얕게 비교한다. 오브젝트 안에 있는 레퍼런스 값들을 deep하게 비교하는 것이 아닌 props를 비교하는데 그 오브젝트 자체가 같다면 데이터가 변화했다고 판단하지 않게 된다. 그렇기 때문에 PureComponent로 선언된 class component는 해당하는 props안에 데이터가 바뀐것을 감지하지 않기 때문에 랜더가 실행되지 않는다.

💡 연관된 것으로 function component에서는 memo를 이용해 랜더 최적화를 할 수 있다.

해당 포스트에 잘못된 정보가 있다면 댓글 남겨주세요!

profile
정리하고 기억하는 곳

0개의 댓글