State는 컴포넌트 내부에서 변할 수 있는 값을 저장하는 것이다.
state를 다룰 때 사용하는 특별한 함수가 필요하다. 바로 useState
import { useState } from "react";
const [state 저장 변수, state 갱신 함수] = useState(상태 초기 값);
function CountExample() {
const [count, setCount] = useState(0);
const handleCount = () => {
setCount(count + 1)
}
return (
<div>
<button onClick={handleCount}></button>
<div>Count: {count}</div>
</div>
)
}
- 컴포넌트는 state가 변경되면 새롭게 호출되어 리렌더링된다.
- state의 변경은 상태 변경 함수 호출로 변경한다. (그냥 재할당으로 변경하기 되면 리렌더링이 되지 않는다거나, state가 제대로 변경되지 않는다.)
컴포넌트의 속성(Property)를 의미한다. 변하지 않는 외부로부터 전달받은 값이다. 보통 부모 컴포넌트(상위 컴포넌트)로 부터 전달받는다. 전달 받은 값이 하위 컴포넌트에 전달인자(argument)처럼 전해지고 그 하위 컴포넌트에서 초기값처럼 사용된다. 또한 읽기 전용이기 때문에 하위 컴포넌트에서는 수정을 할 수 없다.(read-only)
function Parent() {
const hi = "I'm the parent"
return (
<div className="parent">
<h1>{hi}</h1>
<Child text={hi}/>
</div>
)
}
function Child(props) {
return (
<div className="child">{props.text}</div>
)
}
상위 컴포넌트에서 하위 컴포넌트의 속성처럼 전해준다.
하위 컴포넌트는 props를 객체 형태로 받고 그 데이터를 사용할수 있다.
function Parent() {
const hi = "I'm the parent"
return (
<div className="parent">
<h1>{hi}</h1>
<Child>I'm the Child</Child>
</div>
)
}
function Child(props) {
return (
<div className="child">{props.children}</div>
)
}
상위 컴포넌트에서 하위 컴포넌트의 태그 사이 value를 전달해줄 수 있다. 전달된 객체의 children이라는 키값에 있다.
react에서 state와 props가 진짜 중요하다. state와 props를 빼놓고 react를 얘기할 수 없을 것이다.