본문 바로가기

Frontend/React

Props & memo

1. Props

function Btn({text, big}) 에서 text, big은 Btn 컴포넌트에게 줄수있는 props(properties)이다.

여러개의 동일한 컴포넌트 생성 시 마크업이나 스타일을 재사용할 때 유용하다.

  <Btn text="Save Changes" big={true}> // btn text : Save Changes, fontsize : 18

  function Btn({text, big}) {
        return (
        <button style={{
            backgroundColor:"tomato",
            color:"white",
            padding:"10px 20px",
            border:0,
            borderRadius:10,
            fontSize: big ? 18 : 16,
        }}>
        {text}
        </button>
        );
    }
  
    function App() {
      return  (
        <div>
            <Btn text="Save Changes" big={true}/>
            <Btn text="Continue" big={false}/>
        </div>
      );
    }

2. React.memo 

컴포넌트의 props가 바뀌지(changeValue) 않았다면,

리렌더링을 방지(두번째 Btn은 render되지않음)하여 컴포넌트의 리렌더링 성능 최적화를 해줄 수 있다. 

즉, 컴포넌트에서 리렌더링이 필요한 상황에서만 리렌더링을 하도록 설정해줄수있다.

  const MemorizedBtn = React.memo(Btn)
    function App() {
    const [value, setValue] = React.useState("Save Changes");
    const changeValue = () => setValue("Revert Changes");
      return  (
        <div>
            <MemorizedBtn text={value} changeValue={changeValue}/>
            <MemorizedBtn text="Continue" />
        </div>

3. PropTypes

props에 type을 부여해 console에 에러를 표시함으로써 잘못된 입력을 방지한다.

<script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>

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

 

'Frontend > React' 카테고리의 다른 글

To Do List (Enrollent)  (0) 2022.01.22
useEffect  (0) 2022.01.21
Unit Converter  (0) 2022.01.10
JSX란?  (0) 2022.01.04
React vs Vanilla JS  (0) 2022.01.03