반응형
useState는 가장 기본적인 Hook 이며, 가변적인 상태를 지닐 수 있게 해 주는 훅 입니다.
함수 컴포넌트에서 상태 관리를 할 때에는 useState 를 사용할 것입니다.
Counter.js
import {useState} from 'react';
const Counter = () => {
const [value, setValue] = useState(0)
//useState의 파라미터는 기본값을 의미한다. 따라서 0 은 value의 기본값이 된다.
return(
<div>
<p>현재 카운터 값은 {value} 입니다.</p>
<button onClick={()=>{setValue(value + 1)}} >+1</button>
<button onClick={()=>{setValue(value - 1)}} >-1</button>
</div>
);
};
export default Counter;
현재 useState 가 호출되었을 때 [value, setValue] 배열을 반환하는데,
value = 상태값,
setValue = 상태를 설정하는 함수입니다.
따라서 setValue에 파라미터를 넣어서 호출하면 전달받은 파라미터로 값이 바뀌고 컴포넌트가 리렌더링 되는 구조입니다.
그래서 버튼에서 onClick 이벤트에 setValue(value +- 1) 을 전달하여 값을 각각 변경할 수 있게 된 것입니다.
버튼을 눌러보면 정상적으로 값이 추가됩니다.
반응형
'React > basic' 카테고리의 다른 글
[React] Firebase 를 이용한 신규 사용자 가입 (이메일 가입) (0) | 2023.05.16 |
---|---|
[React-Hook] useEffect 란? (0) | 2023.03.21 |
[React] 이미지 넣기 (0) | 2023.03.01 |
[React] 화살표함수와 this의 관계 (1) | 2023.03.01 |
[React] var 대신 let을 사용하자! (0) | 2023.03.01 |