FrontEnd/React

[react] 공부 메모

무무둥 2023. 2. 17. 19:44

- useState 표현

const [counter, setCounter] = React.useState(0);

위와 같이 정의된 counter라는 state 값이 있을 때

1. 특정 값으로 바꾸는 경우

setCounter(12345);

2. 기존의 index 값을 기준으로 바꿀 경우 아래와 같이 써주는 것이 안정성 면에서 우수하다.

setCounter(curIndex => curIndex + 1);

 

- React Memo

React는 state 변경이 일어나면 내부 컴포넌트 전체를 re-render 한다.

그러나 memo를 통해 만들어진 컴포넌트는 본인의 props가 변경되지 않으면 state 변경이 일어나더라도 re-render 하지 않도록 하다.

우측은 memo 기능이 적용된 버튼 컴포넌트

<script>
// 버튼 컴포넌트
function Btn({ text, onClick }) {
  console.log("text", text);
  return <button onClick={onClick}>{text}</button>;
}


// case 1
function App() {
  const [text, setText] = React.useState("first");
  const changeText = () => setText("Change Text!");

  return (
    <div>
      <Btn text={text} onClick={changeText} />
      <Btn text="second" />
    </div>
  );
}

// case 2
const MemorizedBtn = React.memo(Btn);
function App() {
  const [text, setText] = React.useState("first");
  const changeText = () => setText("Change Text!");

  return (
    <div>
      <MemorizedBtn text={text} onClick={changeText} />
      <MemorizedBtn text="second" />
    </div>
  );
}
</script>

 

- PropType

컴포넌트에 전달 받는 props 들의 type을 지정해 주는 기능.

> npm i prop-types

실제로 render 되지 않는것은 아니나 console로 error를 띄워주기 때문에 협업 시 유용하다.

<script>
function Btn({ text, fontSize }) {
  console.log("text", text);
  return <button>{text}</button>;
}

Btn.propTypes = {
  text: PropTypes.string,
  fontSize: PropTypes.number.isRequired, // isRequired 기재할 경우 필수값을 나타낸다.
};
</script>