코드를 작성하다 보면 같은 기능을 여러 개 구현하고자 할 때 반복이 생깁니다.
const [count, setCount] = useState(0);
const [count1, setCount1] = useState(0);
const [count2, setCount2] = useState(0);
const increment = () => {
setCount(count + 1);
};
const increment1 = () => {
setCount1(count1 + 1);
};
const increment2 = () => {
setCount2(count2 + 1);
};
return (
<div className="App">
<button onClick={increment}>Click {count}</button>
<button onClick={increment1}>Click {count1}</button>
<button onClick={increment2}>Click {count2}</button>
</div>
);
각각 똑같은 기능을 하는 Click 버튼 세 개를 만들고자 할 때 같은 코드를 3번이나 중복해서 사용해야 합니다. 이를 컴포넌트를 사용하여 반복을 줄일 수 있습니다.
<컴포넌트의 장점>
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div className="App">
<button onClick={increment}>Click {count}</button>
</div>
);
};
export default Counter;
Click 버튼 기능을 컴포넌트로 만들어 export 해주고, 그 기능을 사용하고자 하는 파일에서 import 해준 뒤 사용할 수 있습니다.
import Counter from './components/Counter';
function App() {
return (
<div className="App">
{/* 컴포넌트 사용 */}
<Counter />
<Counter />
<Counter />
</div>
);
}
export default App;