Web/React
React Hook 01 - useState()
또롱또
2022. 5. 15. 18:37
728x90
- useState()는 react library에서 정의된 자바스크립트 함수이다.
- useState를 호출하면 배열을 반환한다. 첫 번째 원소가 현재 상태를 설정하고, 두 번째 원소는 상태를 갱신해 주는 함수이다.
- const [현재상태, 상태의갱신을도와줌] = useState(현재상태에게 줄 초기값)
- 그냥 html화면에서 자주 갱신되거나 변경될거같은건 state로 빼주면 편하다.
import logo from './logo.svg';
import './App.css';
import { useState } from 'react';
const App = () => {
// count같이 html에서 자주 변할만한거는 state로 빼준다
const [count, setCount] = useState(0);
// state는 이렇게 사용가능
const increment = () => setCount(count+1);
const decrement = () => setCount(count-1);
return (
<div className="App">
<h1>Hello {count}</h1>
<button onClick={increment}>Up</button>
<button onClick={decrement}>Down</button>
</div>
);
}
export default App;
728x90