useState
리액트에서 컴포넌트는 한 번 렌덩이되고 끝나지 않습니다. 리액트의 컴포넌트는 실시간으로 계속 렌더링되는데 일반 변수를 사용하면 성능의 저하를 불러올 수 있습니다.
리액트의 컴포넌트에서 상태를 관리하는 방법 중 하나로는 useState가 있습니다.
useState는 유동적으로 변경될 값을 관리할 때 사용이 됩니다.
useState 사용해보기
- Counter 구현
Counter.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react'; | |
const Counter = () => { | |
const [state, setState] = useState(0) // 초기 상태 값을 0으로 설정 | |
// 증가 | |
const onIncrease = () => { | |
setState(state + 1) | |
} | |
// 감소 | |
const onDecrease = () => { | |
setState(state - 1) | |
} | |
return ( | |
<> | |
<p>{state}</p> | |
<button onClick={onIncrease}>+1</button> | |
<button onClick={onDecrease}>-1</button> | |
</> | |
) | |
} | |
export default Counter; |
초깃 값을 0으로 설정을하고, 버튼을 누르면 증감이 되도록 하였습니다.
App.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import Counter from "./Counter"; | |
const App = () => { | |
return ( | |
<Counter/> | |
) | |
} | |
export default App; |
실행화면

- Random 구현
Random.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from "react"; | |
const Random = () => { | |
const [state, setState] = useState(0) // 초기 상태를 0으로 설정 | |
// 랜덤 값 반환 | |
const randomValue = () => { | |
return Math.floor(Math.random() * (10000)); | |
} | |
const onClick = () => { | |
setState(randomValue()) | |
} | |
return ( | |
<> | |
<p>{state}</p> | |
<button onClick={onClick}>Change</button> | |
</> | |
) | |
} | |
export default Random |
Counter와 마찬가지로 초기 상태는 0으로 설정을 하고 버튼을 누르면 값이 랜덤으로 변하게 구현을 했습니다.
App.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import Random from "./Random"; | |
const App = () => { | |
return ( | |
<Random/> | |
) | |
} | |
export default App; |
실행화면

Github: https://github.com/hanhyung6376/learn-react/tree/master/use-state
'웹 프로그래밍 > React' 카테고리의 다른 글
[React] useEffect (0) | 2021.10.15 |
---|---|
[React] useCallback (0) | 2021.10.13 |
[React] 외부 라이브러리 없이 캘린더 구현 (0) | 2021.10.11 |
[React] withRouter를 이용한 링크 이동시 메뉴변경 (0) | 2021.09.27 |
[ReactJS] JSX (0) | 2021.09.06 |