React에서는 component끼리 데이터를 서로 주고 받을 때 propsstate 를 활용할 수 있다.

Props

  • 부모 컴포넌트가 자식 컴포넌트에 값을 전달할 때 사용하는 것이다 (읽기 전용)


App.js

import "./styles.css";
import { Example1 } from "./Example1";

export default function App() {
  return (
    <div className="App">
      <h1>Props 예제</h1>
      <Example1 str="테스트" />
    </div>
  );
}

Example1 컴포넌트에 ‘테스트’ 라는 문자데이터를 str 이라는 이름으로 props 를 전달한다.


Example1.jsx

export const sExample1 = (props) => {
  return <h1>"{props.str}"</h1>;
};

<h1></h1> 태그 사이에 전달 받은 props 데이터를 입력을 해주면 props 데이터를 받아올 수 있다.


결과

props_example




State

  • state는 컴포넌트 자기 자신이 가지고 있는 값이다.
  • 함수 컴포넌트에서는 useState() Hook을 이용해서 state를 생성할 수 있다.


App.js

import "./styles.css";
import { Example2 } from "./Example2";

export default function App() {
  return (
    <div className="App">
      <h1>Sate 예제</h1>
      <Example2 />
    </div>
  );
}




Example2.jsx

import { useState } from "react";

export const Example2 = () => {
  const [state, setState] = useState(0);
  return (
    <div>
      <button onClick={() => setState(state + 1)}>Click!</button>
      <h1>{state}</h1>
    </div>
  );
};

위 예제에서는
useState() 를 이용해서 state 와 state 값을 변경시킬 수 있는 setState 함수를 만들었다.
<button> 태그를 클릭하면 setState 함수가 호출이 되면서 state 값에 변화를 줄 수 있다.


클릭 전 결과

state_example1

클릭 후 결과

state_example2

<button> 태그를 클릭하면 setState 함수가 호출되면서
<h1></h1> 태그 사이에 작성했던 state 값이 1 증가한 결과를 볼 수 있다.





Props 와 State 에 대한 개념을 확실히 이해하고서
React 프로젝트에 임해야겠다,,😸 </br>