React 최상위 API – React

우측의 setCount(10)이 발생할 때 부모가 리랜더 되는데 이때 TextView는 리랜더 될 필요 없다.

→ 연산의 낭비가 발생!

Untitled

해결 방안!!! (React.memo)

→ 함수형 컴포넌트에게 업데이트 조건을 걸자

Untitled

Untitled

props가 바뀌지 않으면 리렌더링하지 않는 강화된 컴포넌트로 돌려주겠다!

const MyComponent = React.memo(function MyComponent(props) {
  /* props를 사용하여 렌더링 */
});

아래의 코드의 문제는 count가 올라갈 때마다 rerender가 되는데 그때 전혀 상관없는 Textview까지 재실행 된다는 점

import React, { useState, useEffect } from "react";

const Textview = ({ text }) => {
  useEffect(() => {
    console.log(`update :: text : ${text}`);
  });
  return <div>{text}</div>;
};

const CountView = ({ count }) => {
  useEffect(() => {
    console.log(`update :: count : ${count}`);
  });
  return <div>{count}</div>;
};

// Component를 재사용하는 실습용이므로 강의 끝나면 주석처리 !
const OptimizeTest = () => {
  const [count, setCount] = useState(1);
  const [text, setText] = useState("");

  return (
    <div style={{ padding: 50 }}>
      <div>
        <h2>count</h2>
        <CountView count={count} />
        <button onClick={() => setCount(count + 1)}>+</button>
      </div>
      <div>
        <h2>text</h2>
        <Textview text={text} />
        <input value={text} onChange={(e) => setText(e.target.value)} />
      </div>
    </div>
  );
};

export default OptimizeTest;

React.memo 사용!

CountView에서 count가 올라가도 Textview는 실행되지 않는 것을 확인할 수 있다.