React.Component와는 React 메소드중 하나인 shouldComponentUpdate를 다루는 방식이 다르다.
React.PureComponent는 shouldComponentUpdate가 이미 구현되어 있고,
props와 state를 얕은 비교를 한 뒤 변경된 것이 있는경우만 리렌더링한다.
즉, PureComponent는 성능을 향상시키는데 중요한 것인 ShouldComponentUpdate를 신경쓰지 않아도 된다.
밑의 코드는 사용자가 버튼을 클릭하면 카운터가 랜덤하게 증가하는 컴포넌트다.
import React, { PureComponent } from 'react';
import { render } from 'react-dom';
const root = document.querySelector('#root');
const pTag = document.createElement('p');
const logClosure = () => {
let clickedCount = 0;
let reRenderedCount = -1;
return (isReRendered) => {
if (isReRendered) {
reRenderedCount += 1;
} else {
clickedCount += 1;
}
pTag.textContent = `log -> click count : ${clickedCount} | re-render count : ${reRenderedCount}`;
};
};
const log = logClosure();
class App extends PureComponent {
constructor(props) {
super(props);
this.state = {
counter: 0,
};
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
root.after(pTag);
}
handleClick() {
log(false);
if (Math.floor(Math.random() * 10) % 2) {
this.setState({
counter: this.state.counter + 1,
});
} else {
this.setState({
counter: this.state.counter,
});
}
}
render() {
log(true);
return (
<div>
{this.state.counter}
<br />
<input
type="button"
onClick={this.handleClick}
value="click"
/>
</div>
);
}
}
render(<App />, root);
PureComponent를 사용하면 카운트가 증가할 때만 re-render 하지만
Component를 사용하면 setState가 실행되어, 매 클릭마다 re-render 한다.
this.state.counter는 0부터 10까지의 랜덤한 값을 받아 그게 2로 나눠지는 수 ( 짝수 )
인 경우에만 counter가 1씩 늘어나게되는데
이 counter에 변화가 생긴경우에만 re-render가 되는게 PureComponent다
'프로그래밍 > React.js' 카테고리의 다른 글
Typescript - 이차원배열 타입 정의 , event의 Type 정의 (0) | 2021.04.10 |
---|---|
TypeScript 복습하기 #1 초기세팅 (0) | 2021.01.12 |
CRA TypeScript로 생기는 tsconfig.json 뜯어보기 (0) | 2021.01.10 |
React Dev Tools 업데이트 되고나서 Highlight Updates가 사라짐? (0) | 2019.08.23 |