지난번에 rerendering의 중요성에 대해 배웠다.
리액트는 고맙게도 이 과정마저 React.useState()를 통해 간편화시켜준다.
<!DOCTYPE html>
<html lang="en">
<body>
<div id="root"></div>
</body>
<!-- How to import React(engine) -->
<script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script>
<!-- How to import React-dom(put elements into HTML) -->
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script>
<!-- How to make browser read JSX syntax (using babel)-->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
const root = document.getElementById("root");
function App () {
// unpacking
const [counter, setCounter] = React.useState(0);
const onClick = () => {
// modifier rerenders component itself
setCounter(counter + 1);
}
return (
<div>
<h3>Total clicks: {counter}</h3>
<button onClick={onClick}>Click me</button>
</div>
)
}
// initial render
ReactDOM.render(<App />, root);
</script>
</html>
function App () {
// unpacking
const [counter, setCounter] = React.useState(0);
const onClick = () => {
// modifier rerenders component itself
setCounter(counter + 1);
}
return (
<div>
<h3>Total clicks: {counter}</h3>
<button onClick={onClick}>Click me</button>
</div>
)
}
주목할 부분은 윗 부분인데,
React.useState(0) 는 변수와 함수를 만들어낸다.
그리고 각각은 [] 즉 리스트로 변환가능하다.
setCounter의 역할은 앞 변수를 받아
이를 함수처리해주고 다시 rerendering해준다는 것이다.
'FrontEnd > React' 카테고리의 다른 글
| [ReactJS] prop에 대한 이해 (0) | 2023.01.08 |
|---|---|
| [ReactJS] input, form (0) | 2023.01.07 |
| [ReactJS] render, rerender (0) | 2023.01.05 |
| [ReactJS] JSX 문법 (0) | 2023.01.05 |
| [ReactJS] JSX 문법과 babel 설치하기 (0) | 2023.01.05 |