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>
);
}
useState
는 인자로 초기 state
값을 하나 받는다. 카운터는 0부터 시작하기 때문에 위 예시에서는 초기값으로 0을 넣어준 것이다. this.state
와는 달리 setState Hook
의 state
는 객체일 필요가 없다. 이 초기값은 첫 번째 렌더링에만 딱 한번 사용된다.
useState
는 state
변수, 해당 변수를 갱신할 수 있는 함수 이 두 가지 쌍을 반환한다. 이것이 바로 const [count, setCount] = useState()
라고 쓰는 이유이다. 클래스 컴포넌트의 this.state.count
와 this.setState
와 유사하다.
function ExampleWithManyStates() {
// 상태 변수를 여러 개 선언
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
// ...
}
const Example = (props) => {
// 여기서 Hook을 사용할 수 있다.
return <div />;
}
<p>You clicked {count} times</p>
클래스 컴포넌트는 count를 보여주기 위해 this.state.count
를 사용했지만 함수 컴포넌트는 count를 직접 사용할 수 있다.
<button onClick={() => setCount(count + 1)}>
Click me
</button>
클래스 컴포넌트는 count를 갱신하기 위해 this.setState()
를 호출했지만 함수 컴포넌트는 setCount와 count 변수를 가지고 있으므로 this
를 호출하지 않아도 된다.