본문 바로가기
Study/Udemy-React-완벽 가이드

12. React.memo (feat. 유데미 React 완벽 가이드)

by NFAP0221S 2022. 6. 4.

https://www.udemy.com/course/best-react/

 

【한글자막】 React 완벽 가이드 with Redux, Next.js, TypeScript

Javascript부터 웹 어플리케이션 배포까지, React와 프론트엔드 최신 기술을 가장 쉽고 확실하게 배우는 법

www.udemy.com

이 게시물은 유데미 React 완벽 가이드 강의를 보고 메모를 남기는 게시물 입니다.


React.memo 

  • 최적화에 사용한다.
  • props의 값이 바뀌지 않았는데 컴포넌트가 실행되는 경우에 사용한다. 

React.memo 는 인자로들어간 컴포넌트의 Props 과 이 컴포넌트의 자식의 컴포넌트 Props 모두를 확인하여

기억한 다음, 입력되는 최신의 Props 의 값과 비교하여 값이 바뀌었을 경우에만 컴포넌트를 재실행 해준다.

사용해보기

최상위 부모인 App.js 이다.

사용자 정의 컴포넌트로 DemoOut과 Button이 있고  DemoOut은 자식으로 MyParagraph 컴포넌트를 가지고 있다.

App.js

function App() {
  const [showParagraph, setShowParagraph] = useState(false);

  console.log("앱 러닝");

  const toggleParagraphHandler = () => {
    setShowParagraph((prevShowParagraph) => !prevShowParagraph);
  };

  return (
    <div className="app">
      <h1>Hi there!</h1>
      <DemoOutput show={false} />
      <Button onClick={toggleParagraphHandler}>Show Paragraph!</Button>
    </div>
  );
}

export default App;

Button.js

const Button = (props) => {
  console.log("버튼 러닝");
  .
  .
  .
  생략

DemoOutput.js

const DemoOutput = (props) => {
  console.log("데모아웃 러닝");
  return <MyParagraph>{props.show ? `This is new!` : ""}</MyParagraph>;
};

export default DemoOutput;

 

MyParagraph.js

const MyParagraph = (props) => {
  console.log("마이파라그래프 러닝");
  return <p>{props.children}</p>;
};

첫 랜더링에서 콘솔출력으로

앱 러닝, 버튼 러닝, 데모아웃 러닝, 마이파라그래프 러닝 이 출력된다.

Console

버튼을 누르면 최상위 부모인 App 에서 "앱 러닝" 과 버튼에서의 "버튼 러닝" 만 출력하고 싶은데

모든 컴포넌트의 콘솔이 출력된다.

 

이를 최적화 하기위해 DemoOutpu에 React.memo 를 사용하면 props이 변하지 않는 컴포넌트의 실행을 막을 수 있다.

그리고 위에서 언급했듯이 DemoOutput의 자식인 MyParagraph도 React.memo 가 적용이 된다.

const DemoOutput = (props) => {
  console.log("데모아웃 러닝");
  return <MyParagraph>{props.show ? `This is new!` : ""}</MyParagraph>;
};

export default React.memo(DemoOutput);