useState는 [state, setState]
첫 번째 인자인 state를 제공하고,
state와 state를 변경 할 두 번째 인자 setState 함수를 반환한다.
또한, initialState를 파라미터로 받는다.
const Example = () => {
const [count, setCount] = useState(3);
비구조화 할당 문법을 통해 state에는 count를
setState엔 setCount로 받아서 사용할 수 있다.
setCount로 count state를 변경하면 렌더링이 다시 일어남.
Example은 함수이기 때문에, 렌더링 할 컴포넌트 대신에
값을 반환할 수 있음.
import { useState } from 'react';
const Example = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>{`count: ${count}`}</p>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
)
};
export default Example;
import { useState } from 'react';
const [count, setCount] = useState(0);
useState(0);
<button onClick={() => setCount(count + 1)}>+</button>
<p>{`count: ${count}`}</p>