본문 바로가기

React

[React] state와 props에 차이점.

리액트에서 흔히 쓰이는 state와 props 둘의 사용법은 대략 비슷하다.

하지만 분명 차이점이 있고 사용방법도 차이가 있다.

 

State

import React, { useState } from 'react';

function Example() {
  // "count"라는 새 상태 변수를 선언합니다
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

 

props

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

 

 

Props

- 읽기 전용(변할 수 없다.)

- 부모 요소(컴포넌트)에서 선언되어야 하며 변경도 부모요소(컴포넌트)에서 되어야한다.

 

State

- props와의 차이점은 변할 수 있다.

- 변화시에는 리렌더링이 일어난다.