전에 봤던 vanilla js 의 counter 프로그램을 React로 만든다고 한다면,
App.js
import React from "react";
import Counter from "./components/Counter"
function App() {
return (
<Counter />
);
}
export default App;
기본적으로 Counter 이라는 Component 를 이용하여 count increment, decrease 를 하는 코드를 만들어 볼것입니다.
Component.js
import React, { useState } from "react";
const Counter = () => {
const [count, setCount] = useState(0);
const onIncrease = () => {
setCount(count + 1);
};
const onDecrease = () => {
setCount(count - 1);
};
return (
<div>
<h2>{count}</h2>
<button onClick={onIncrease}>+</button>
<button onClick={onDecrease}>-</button>
</div>
);
};
export default Counter;
userState 함수를 불러오게 되어 count, setCount 라는 state를 활용하여 데이터를 수정하게 되고
vanilla js로 짠 코드보다 훨씬 간결하고 가독성이 좋아진 것을 볼 수 있습니다.
inflearn의 한입-리액트 강좌를 보고 많이 참고 했습니다.
'FrontEnd > React' 카테고리의 다른 글
React - useEffect (0) | 2022.03.27 |
---|---|
React - useRef DOM 제어 (0) | 2022.03.25 |
React & Node.js 연동하기 (0) | 2022.03.24 |
React - Props (0) | 2022.03.23 |
React 왜 배우는 것 일까? (0) | 2022.03.17 |