해나아부지 개발일지

props vs state 본문

Developers/React

props vs state

__APPA 2020. 8. 23. 20:21

React에서 데이터를 다룰 때 props(properties: 속성)를 써야하는지 state(상태)를 써야하는지 구분하는 것은 매우 중요하다.

 

정적(static) vs 동적(dynamic)

React의 근간이 되는 컴포넌트(Component)는 Tree 구조처럼 계층을 갖는다. props는 정적인 데이터이다. 쉽게 말해 상위 컴포넌트(부모 컴포넌트)의 데이터를 전달받아 사용하는 데이터이다. 반면 state는 동적인 데이터이다. 클라이언트에서 유저의 요청 및 이벤트 혹은 비동기처리 등에 의해 실시간으로 변화하는 데이터이다. 

 

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

App이라는 부모 컴포넌트의 자식 컴포넌트로 '<Welcome />'이라는 컴포넌트가 사용되어지고 있는데 각 컴포넌트에 다른 props들이 전달이 되는 것을 볼 수 있다. Javascript에서 parameter를 받아서 실행되는 함수를 생각해보면 이해가 쉬울 것 같다. Welcome 이란 함수형 컴포넌트에 "Sara", "Cahal", Edite"가 props를 통해서 전달이 되는데 여기서 props가 객체이고 name이라는 key에 "Sara", "Cahal", Edite" 각각 value로 들어가서 사용되어 진다고 보면 되겠다.

 

state는 React.Component를 상속 받는 class component에서만 사용할 수 있다. class component의 instance가 생성될 때에 'Life Cycle'이 생기는데 이 Cycle을 통해서 state의 상태에 변화를 줄 수 있다. 

 

import React from 'react'

class Counter extends React.Component {
    constructor(props) { 
        super(props)
        this.state = {
            count: 0
            }
    }

    
 increment() {
   this.setState({count: this.state.count + 1})
   }
    
 decrement() {
   this.setState({count: this.state.count - 1})
   }
   
   render() {
     return (
       <div>
         <span>{this.state.count}</span>
         <button onClick={this.increment.bind(this)}>add</button>
         <button onClick={this.decrement.bind(this)}>minus</button>
       </div>)
   }
}

 

class의 state는 직접적으로 변경 할 수 없고 this.setState()를 통해서만 변경을 해야한다. 직접적으로 state를 건드리면 오류가 떠서 친절하게 setState를 사용하라고 알려준다. 

 

부모-자식 컴포넌트 관계가 많아질수록 자식 컴포넌트에서 부모 컴포넌트에 state를 변경해줘야 될 때가 있다. state 끌어올리기라는 기법을 사용하여 자식 컴포넌트에서의 state 변화 요청을 할 수가 있다. React에서는 함수를 컴포넌트의 props로 전달할 수가 있다. 해서 자식 컴포넌트에 전달된 함수로 이벤트 요청을 하면 부모 컴포넌트의 함수를 실행한 것이기 때문에 부모 컴포넌트의 state를 변경할 수 있다.

 

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

React Start  (0) 2020.09.02
Redux란?  (0) 2020.08.25
JSX  (0) 2020.08.20
React Component Life Cycle  (0) 2020.08.08
Set up for beginner (create-react-app)  (0) 2020.07.21
Comments