React/Concept

[ React ] Props

Design-loving front-end engineer 2022. 7. 14. 10:58

⚪  컴포넌트에 추가한 argument들은 컴포넌트에 Object로 전달되며, 이를 Destructing 하여 원하는 속성만 적을 수 있다.

⚪  부모 컴포넌트의 어떠한 state 변화가 생기면 자식 컴포넌트들은 모두 리렌더링된다.

⚪  따라서, props가 변하지 않는 컴포넌트까지 모두 리렌더링되며, 이는 성능 저하의 원인이 될 수 있다.

⚪  이를 방지하기 위하여 memo를 사용하여 리렌더링 할 필요가 없는 컴포넌트들을 최적화시킬 수 있다.

⚪  리액트 js는 컴포넌트 타입에 대해 오류를 출력하지 않는다. 따라서, prop-types 라이브러리를 통해서 타입과 필요성을 명시할 수 있다.

 
const Btn = ({ text, fontSize }) => {
  return (
    <button
      style = {
        backgroundColor: "tomato",
        color: "white",
        padding: "10px 20px",
        border: 0,
        borderRadius: 10,
        fontSize,
      }
    >
      {text}
    </button>
  );
}
const MemorizedBtn = memo(Btn);

Btn.propTypes = {
  text: PropTypes.string.isRequired,
  fontSize: PropTypes.number,
};

const App = () => {
  return (
    <div>
      <MemorizedBtn text="Save Changes" fontSize={18} />
      <MemorizedBtn text="Continue" />
    </div>
  );
}