PureComponent๊ฐ Component์ ๋ค๋ฅธ ์ ์ React์ ์๋ช
์ฃผ๊ธฐ ๋ฉ์๋์ค ํ๋์ธ shouldComponentUpdate
๋ฅผ ์ด๋ป๊ฒ ์ฐ๋๊ฐ ํ๋ ๋ถ๋ถ์ด๋ค.
์์ ๋น๊ต (shallow-compare)
1. ๋ณ์์ ๋ฌธ์์ด์์๋ ๊ฐ์ ๋น๊ตํ๋ค.
2. ๊ฐ์ฒด์์๋ reference ๊ฐ์ ๋น๊ตํ๋ค.
Component๋ shouldComponentUpdate
๋ฅผ ๋ฐ๋ก ์ค์ ํด์ฃผ์ง ์์ ๊ฒฝ์ฐ ํญ์ true๋ฅผ ๋ฐํํ๋ค. ๋ฐ๋ผ์, setState๊ฐ ์คํ๋๋ฉด state, props์ ๋ณ๊ฒฝ ์ฌ๋ถ๋ฅผ ์ ๊ฒฝ์ฐ์ง ์๊ณ ๋ฌด์กฐ๊ฑด์ ์ผ๋ก Component๋ฅผ ์
๋ฐ์ดํธํ๋ค.
ํ์ง๋ง PureComponent์ ๊ฒฝ์ฐ ํ์ฌ state, props์ ๋ฐ๋ state, props๋ฅผ ๋น๊ตํ์ฌ ์
๋ฐ์ดํธ ์ฌ๋ถ๋ฅผ ๊ฒฐ์ ํ๊ฒ ๋๋ ๊ฒ์ด๋ค.
React.memo๋ ๊ณ ์ฐจ ์ปดํฌ๋ํธ(Higher Order Component)์ด๋ค.
props๊ฐ ๊ฐ๋ ๋ณต์กํ ๊ฐ์ฒด์ ๋ํ์ฌ ์์ ๋น๊ต๋ง์ ์ํํ๋ ๊ฒ์ด ๊ธฐ๋ณธ ๋์์ด๋ค. ๋ค๋ฅธ ๋น๊ต ๋์์ ์ํ๋ค๋ฉด, ๋ ๋ฒ์งธ ์ธ์๋ก ๋ณ๋์ ๋น๊ต ํจ์๋ฅผ ์ ๊ณตํ๋ฉด ๋๋ค.
Ref๋ render ๋ฉ์๋์์ ์์ฑ๋ DOM ๋ ธ๋๋ React ์๋ฆฌ๋จผํธ์ ์ ๊ทผํ๋ ๋ฐฉ๋ฒ์ ์ ๊ณตํ๋ค.
์์
this.input.current
๋ฅผ ์กฐํํ๋ฉด ๋๋ค.class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = null;
this.setTextInputRef = element => {
this.textInput = element;
};
this.focusTextInput = () => {
// DOM API๋ฅผ ์ฌ์ฉํ์ฌ text ํ์
์ input ์๋ฆฌ๋จผํธ๋ฅผ ํฌ์ปค์คํ๋ค.
if (this.textInput) this.textInput.focus();
};
}
componentDidMount() {
// ๋ง์ดํธ ๋์์ ๋ ์๋์ผ๋ก text ํ์
์ input ์๋ฆฌ๋จผํธ๋ฅผ ํฌ์ปค์คํ๋ค.
this.focusTextInput();
}
render() {
// text ํ์
์ input ์๋ฆฌ๋จผํธ์ ์ฐธ์กฐ๋ฅผ ์ธ์คํด์ค์ property
// (์๋ฅผ ๋ค์ด`this.textInput`)์ ์ ์ฅํ๊ธฐ ์ํด `ref` ์ฝ๋ฐฑ์ ์ฌ์ฉํ๋ค.
return (
<div>
<input
type="text"
ref={this.setTextInputRef}
/>
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
shouldComponentUpdate
๋ฅผ ์ ๊ฒฝ์ฐ์ง ์์๋ ๋๋ ๊ฒ์ PureComponent์ React.memo ๋ ๋ค ํด๋น๋๋ ๊ฒ ๊ฐ์๋ฐ, ์ด๋จ ๋ PureComponent๋ฅผ ์ฌ์ฉํ๊ณ React.memo๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ธ์ง๋ ์์ง ์ ๋ชจ๋ฅด๊ฒ ๋ค.