[React] State 와 Props

woodylovesboota·2023년 8월 17일
0
post-thumbnail

React JS의 기본적인 스킬 State, Props에 대해 알아보자.

State


처음 React를 공부하며 사용했던 예제인 counter를 create-react-app을 이용해서 만들어보자.

function App() {
  let counter = 0;

  return (
    <div>
      <h2>Total clicks: {counter}</h2>
      <button
        onClick={() => {
          counter++;
        }}
      >
        click me
      </button>
    </div>
  );
}

export default App;

button을 클릭할 때 마다 counter가 하나씩 증가하고 이를 확인할 수 있게 만들었다.

하지만 react를 실행시켜보면 counter가 증가하지 않는다.

counter가 증가하지 않는 경우일 수도 있으니 counter의 값을 확인해보자.

<button onClick={() => {
  counter++;
  console.log("counter : ", { counter });
}}>

counter는 정상적으로 증가하는 것을 알 수 있다.

따라서 실제 counter의 값은 증가하지만 브라우저에서 이를 업데이트 하지 않기 때문에 우리는 증가한 counter를 확인할 수 없는 것이다.

위와 같은 문제를 해결할 수 있는 방법이 바로 state 사용 이다.

React Docs에는 다음과 같이 설명되어 있다.

When state changes, the component responds by re-rendering.

state가 변경되면 component가 re-rendering, 즉 새로고침 된다고 한다.

State 사용하기

Docs에 state를 사용하는 방법에 대해 나와있다. 바로 useState Hook을 이용하는 방법이다. 마침 예제도 counter 증가 예제이니 만들어보며 더 알아보자.

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

React에서 component를 만드는데 크게 두가지 방법이 존재한다. function과 class를 이용하는 것인데, Hook을 이용하면 class를 이용하지 않아도 state를 사용할 수 있게 해준다.

What do we pass to useState as an argument?

The only argument to the useState() Hook is the initial state.

useState()의 유일한 argument는 state의 초기값 이다. counter의 초기값은 0이니 useState(0)을 사용해준다.

What does useState return?

It returns a pair of values: the current state and a function that updates it. This is why we write const [count, setCount] = useState().

useState()의 return 값은 (현재 state값 , state를 업데이트 하는 함수) 쌍 이다. 또한 이는 array 형식으로 반환된다.

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

setCounter()에 업데이트 하고자 하는 값을 넣고 실행시키면 counter가 변경된다. 동시에 App component가 Re-rendering 된다.

이제 useState()를 이용해 counter를 만들어보았다.

import { useState } from "react";

function App() {
  const [counter, setCounter] = useState(0);
  return (
    <div>
      <h2>Total clicks: {counter}</h2>
      <button
        onClick={() => {
          setCounter((prev) => prev + 1);
        }}
      >
        click me
      </button>
    </div>
  );
}

export default App;

counter가 증가하면서 동시에 브라우저 역시 새로고침 되는 것을 알수 있다.

Props


Docs에서 props를 다음과 같이 설명하고 있다.

Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

component는 props라는 input을 받아 React element를 반환한다고 한다. 따라서 props는 component의 input이다.

Props 사용하기

props를 사용해보기 위해 예제에 component를 만들어 보자.

const Button = () => {
  return <button>increase</button>;
};

이름이 Button인 component를 생성했다. 이제 App component에 Button을 추가하자.

// App
return (
  <div>
  	<h2>Total clicks: {counter}</h2>
	<Button/>
  </div>
);

이 때 button을 하나 더 만들고 싶으면 어떻게 해야할까? 가장 단순한 방법은 Button component를 하나 더 만드는 것이다.

const ButtonIncrease = () => {
  return <button>increase</button>;
};

const ButtonDecrease = () => {
  return <button>decrease</button>;
};

하지만 버튼을 만들때마다 component를 만들어줘야 하기 때문에 효율적인 방법은 아니다. 이 때 props를 사용한다.

props는 function component의 input으로 사용되니 다음과 같이 사용할 수 있다.

const Button = (props) => {
  return <button></button>;
};
<Button name="increase" />

Component에 속성을 넣는것 처럼 props에 전달할 값을 작성하면 props에 값이 전달되게 된다.

브라우저에서 props를 확인해보면 Object가 생성되었고 그 안에 내가 넣어준 name: "increase" 가 들어가 있는 것을 알 수 있다.

이제 props를 이용해 하나의 component로 속성이 다른 여러개의 button을 만들 수 있다.

import { useState } from "react";

const Button = (props) => {
  return <button>{props.name}</button>;
};

function App() {
  const [counter, setCounter] = useState(0);

  return (
    <div>
      <h2>Total clicks: {counter}</h2>
      <Button name="increase" />
      <Button name="decrease" />
    </div>
  );
}

export default App;

마지막으로 button에 event handler를 추가해야 한다. props에는 값 뿐만 아니라 함수도 전달할 수 있다.

Props를 이용해 button의 onClick event listener를 전달해 보자.

먼저 Button에 전달해줄 함수를 만든다. counter를 증가/감소 시킬 increaseCounter/decreaseCounter를 만들었다.

이후 함수를 각각 Button component에 props로 추가한다.

<Button name="increase" func={increaseCounter} />
<Button name="decrease" func={decreaseCounter} />

마지막으로 props로 전달된 함수를 onClick event listener에 추가해준다.

const Button = (props) => {
  return <button onClick={props.func}>{props.name}</button>;
};

전체 코드는 다음과 같다.

import { useState } from "react";

const Button = (props) => {
  return <button onClick={props.func}>{props.name}</button>;
};

function App() {
  const [counter, setCounter] = useState(0);

  const increaseCounter = () => {
    setCounter(counter + 1);
  };

  const decreaseCounter = () => {
    setCounter(counter - 1);
  };

  return (
    <div>
      <h2>Total clicks: {counter}</h2>
      <Button name="increase" func={increaseCounter} />
      <Button name="decrease" func={decreaseCounter} />
    </div>
  );
}

export default App;

0개의 댓글

관련 채용 정보