이번 포스트에서는 PureComponenet와 Componenet의 차이에 대해 알아보려 합니다.
클래스형 컴포넌트 - Component Class
클래스현 컴포넌트에는 두 종류가 있는데 이 두 종류가 바로 Component 클래스와 PureComponent 클래스입니다. 일반적으로 알고있는 Component 클래스의 졍우 props와 state, 생명주기함수가 들어있는 구조의 컴포넌트를 제작할 때 사용합니다. 다음과 같은 구조를 띄고 있습니다.
import React from 'react';
class ExampleComponent extends React.Component {
constructor(props) {
super(props);
console.lod('생성자');
}
componentDidMount() { }
render() {
return ();
}
}
export default MyComponent;
PureComponent Class
PureComponent 클래스는 Component 클래스를 상속받은 클래스입니다. 즉, Component 클래스와 똑같은 기능을 하고, 투가적인 기능이 더 탑재 되어 있습니다. PureComponent 클래스는 shouldComponentUpdate()
함수를 '얕은 비교' 하도록 설계되어 있습니다. 즉, '얕은 비교'를 통해 어떠한 데이터가 변경되었을때에만 render()
함수를 호출합니다. Component 클래스는 이와는 상관없이 항상 render()
함수를 호출합니다.
PureComponent에서는 얕은 비교를 위해서 shallow-equal라이브러리의 shallowEqual()
함수가 사용되었습니다. PureComponent의 shouldComponentUpdate()
에서는 다음과 같은 작업을 추가적으로 거칩니다.
shouldComponentUpdate(nextprops, nextstate) {
return !shallowEqual(this.props, nextprops) || !shallowEqual(this.state, nextState)
}
/*이게 이해가 안된다면...*/
shouldComponentUpdate(nextprops, nextstate) {
if(/*값이 변했어요?*/) {
//그럼render하세요
}
else {//변하지 않았으면
//render X
}
}
얕은 비교를 한다는 것은 변수와 문자열에서는 값을 비교하고, 객체에서는 참조(reference)값의 변화를 본다는 것입니다. 이렇게 되면 state나 props 값이 따로 변경되지 않았을 때 생기는 불필요한 render()
함수의 실행을 막을 수 있습니다.
'React' 카테고리의 다른 글
[React]컨텍스트 API (0) | 2021.01.10 |
---|---|
[React] 컨텍스트 개념 이해하기 (0) | 2021.01.10 |
[React]컴포넌트 생명주기(Component LifeCycle)파악하기 (0) | 2021.01.05 |
[React/Component]React 컴포넌트란? (0) | 2020.12.17 |