React - Props / State

황영훈·2024년 4월 27일

리액트 - REACT

목록 보기
3/5
post-thumbnail

▶️ Props

  • 컴포넌트 간의 효율적인 데이터 흐름을 가능하게 하는 객체
  • 단방향 데이터 : 부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달할 때 사용
  • 읽기 전용 데이터 : 자식 컴포넌트에서는 데이터 변경할 수 없다.
    (props는 순수 함수처럼 동작해야된다.)
  • props는 정적인 데이터를 전달한다.
  • props를 전달할 때는 문자열을 제외하고는 { }에 담아서 전달해야 한다.

▪️ 클래스형 컴포넌트에서 props 사용

// 부모 컴포넌트
class App extends React.Component {
  render() {
    return <Body content="안녕" />;
  }
}

// 자식 컴포넌트
class Body extends React.Component {
  render() {
    return <div>{this.props.content}</div>;
  }
}

App이라는 부모 컴포넌트에서 자식 컴포넌트 Body로 content = "안녕" 이라는 데이터를 전송하고 있다.
전송받은 props 데이터는 this.props 키워드를 통해 호출할 수 있다.

▪️ 함수형 컴포넌트에서 props 사용

// 부모 컴포넌트
function App(){
  return(
    <Body content="안녕" />;
  );
}

// 자식 컴포넌트
function Body(props){
  return(
    <div>{props.content}</div>;
  );
}

함수형 컴포넌트도 클래스형 컴포넌트와 마찬가지로 부모 컴포넌트에서 자식 컴포넌트로 props를 전달한다. 차이점은 this를 사용할 필요가 없다.


▶️ State

  • state는 컴포넌트 내부에서 동적인 데이터를 다룬다.
  • 컴포넌트 안에서 데이터를 변경할 수 있다.
  • setState()로 state를 변경한다.
  • setState로 state 변경 시 컴포넌트가 리렌더링 된다.

▪️ 클래스형 컴포넌트에서 state 사용

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

  incrementCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

클래스 컴포넌트에서 state는 생성자(constructor) 내부에서 초기 상태(state)를 설정한 후에 this.state로 호출한다.
setState(updater, [callback])구조로 state를 변경할 수 있다.

  • updater : 새 상태 값을 계산하기 위해 이전 상태를 사용하는 함수 또는 새로운 상태 값. 이 값은 함수이거나 객체일 수 있다.
  • callback (옵션) : setState가 완료된 후에 호출되는 함수. 이 콜백 함수는 상태 업데이트와 관련된 모든 리렌더링이 완료된 후에 실행된다.

▪️ 함수형 컴포넌트에서 state 사용

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  const incrementCount = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={incrementCount}>Increment</button>
    </div>
  );
};

함수형 컴포넌트에서는 State를 사용하기 위해 useState라는 훅(Hook)을 사용한다.
const [state, setState] = useState(initialState); 구조로 상태를 설정한다.

  • state : 컴포넌트의 상태를 저장하는 변수. 상태 변수에는 컴포넌트의 상태 데이터가 저장된다.
  • setState : 상태를 업데이트하는 함수. 이 함수를 호출하여 상태를 변경하고 컴포넌트를 리렌더링할 수 있다.
  • useState : React Hook인 useState를 호출하여 상태를 추가하고 관리한다.
  • initialState : 상태의 초기값. 컴포넌트가 처음 렌더링될 때 사용되는 초기값으로, 상태를 변경하려면 이 값이 사용된다.

* 참고 :
https://ko.legacy.reactjs.org/docs/components-and-props.html
https://ko.legacy.reactjs.org/docs/components-and-props.html
https://minjung-jeon.github.io/React-props-state/

https://firework-ham.tistory.com/29

profile
Faithfulness makes all things possible.

0개의 댓글