본문으로 건너뛰기

React의 State

State? Props?

State? Props?

  • props는 상위 컴포넌트에서 하위 컴포넌트로 전달 해 주어서, 하위 컴포넌트에서 해당하는 값을 노출 시킬 수 있도록 해 줌
  • props는 상위 컴포넌트에서 하위 컴포넌트로 전달 해 주는 값 이기 때문에, 실제로 props가 사용되는 컴포넌트 내부에서는 그 값을 바꿀 수 없음
  • state는 리액트 컴포넌트 "내부" 에서 바꿀 수 있는 값을 의미
  • Props are passed from parent components to child components, allowing child components to display the corresponding values
  • Since props are values passed from parent to child components, they cannot be modified within the component where they are used
  • State refers to values that can be changed "inside" a React component

클래스형 컴포넌트의 State

State in Class Components

State를 사용하기 위해서는 클래스 내부에 아래와 같이 선언 해 준다

To use State, declare it inside the class as shown below

constructor(props) {
super(props);
this.state = {
number: 0,
};
}

실제 사용되는 모습

Actual usage example

import React, { Component } from "react";

export default class TestStateClassComponent extends Component {
constructor(props) {
super(props);
this.state = {
number: 0,
};
}

render() {
const { number } = this.state;

return (
<div>
<h4>{number}</h4>

<button
onClick={() => {
this.setState({ number: number + 1 });
}}
>
+1
</button>
</div>
);
}
}

함수형 컴포넌트의 State

State in Functional Components

함수형 컴포넌트에서 state를 사용하기 위해 아래와 같이 작업 해 준다

To use state in functional components, set it up as follows

import React, { useState } from "react";

const [message, setMessage] = useState();

실제 사용되는 모습

Actual usage example

import React, { useState } from "react";

export default function TestFuncComponent() {
const [message, setMessage] = useState();
const onClickEnter = () => setMessage("안녕하세요!");
const onClickLeave = () => setMessage("안녕히가세요!");

return (
<div>
<h3>{message}</h3>
<button onClick={onClickEnter}>입장</button>
<button onClick={onClickLeave}>퇴장</button>
</div>
);
}

state에 기본 값을 넣어 줄 수 도 있다

You can also set a default value for state

const [message = "React입니다", setMessage] = useState();