당신의 컴포넌트가 동일한 props로 동일한 결과를 렌더링해낸다면, React.memo를 호출하고 결과를 메모이징(Memoizing)하도록 래핑하여 경우에 따라 성능 향상을 누릴 수 있습니다. 즉, React는 컴포넌트를 렌더링하지 않고 마지막으로 렌더링된 결과를 재사용합니다.
구성
Testing은 간단하게 3가지를 진행했습니다.
- React.Memo가 모두 없는 경우
(SecondChildApp, SecondChildwithoutMemo에 props 전달 X)
- React.Memo가 SecondChildwithoutMemo에만 없는 경우
(SecondChildApp, SecondChildwithoutMemo에 props 전달 X)
- React.Memo가 SecondChildwithoutMemo에만 없는 경우
(SecondChildApp, SecondChildwithoutMemo에 props 전달 O)
ReactMemoApp.js
import React, {useState} from 'react';
import FirstChildApp from "./FirstChildApp";
function ReactMemoApp(props) {
const [reactNum, setReactNum] = useState(0);
return (
<div>
{console.log(reactNum)}
<FirstChildApp reactNum={reactNum}/>
<button onClick={() => setReactNum(reactNum + 1)}>ReactMemo Testing</button>
</div>
);
}
export default ReactMemoApp;
FirstChildApp.js
import React from 'react';
import SecondChildApp from "./SecondChildApp";
import SecondChildAppwithoutMemo from "./SecondChildAppwithoutMemo";
function FirstChildApp(props) {
return (
<div>
{props.reactNum}
{/*props 전달 X*/}
{/*<SecondChildApp/>*/}
{/*<SecondChildAppwithoutMemo/>*/}
{/*props 전달 O*/}
<SecondChildApp reactNum={props.reactNum}/>
<SecondChildAppwithoutMemo reactNum={props.reactNum}/>
</div>
)
}
export default FirstChildApp;
SecondChildApp.js
import React from 'react';
function SecondChildApp(props) {
return (
<div>
{console.log('Render with ReactMemo')}
ReactMemo
</div>
);
}
export default React.memo(SecondChildApp);
// React.Memo 없는 경우
// export default SecondChildApp;
SecondChildAppwithoutMemo
import React from 'react';
function SecondChildAppwithoutMemo(props) {
return (
<div>
{console.log('Render without ReactMemo')}
Without ReactMemo
</div>
);
}
export default SecondChildAppwithoutMemo;
React.Memo가 모두 없는 경우
(SecondChildApp, SecondChildwithoutMemo에 props 전달 X)
React.Memo가 SecondChildwithoutMemo에만 없는 경우
(SecondChildApp, SecondChildwithoutMemo에 props 전달 X)
React.Memo가 SecondChildwithoutMemo에만 없는 경우
(SecondChildApp, SecondChildwithoutMemo에 props 전달 O)
React.Memo는 props가 변경되지 않았지만 불필요하게 다시 렌더링되는 Component가 발생하지 않도록 도움을 줍니다. 그렇다면 모든 Component에 React.Memo를 적용하면 성능을 더 향상시킬 수 있을까요?
그렇지 않습니다. React.Memo는 렌더링을 하기 전에 props에 대하여 비교하는 과정을 거치게 됩니다. 결국 많은 Component가 있지만 대부분 props 변경이 없는 경우는 오히려 성능을 저하시키는 원인이 될 수 있습니다. 따라서 필요한 부분에 적절하게 사용한다면 성능을 향상시킬 수 있지만, 과도한 사용은 오히려 성능을 저하시킬 수 있습니다.
감사합니다.