
App 컴포넌트에 모든 기능을 입력하면 켜기 끄기 기능을 했을 때, 카운트 기능도 같이 동작 되는 불편함이 발생한다.
→ 각각의 기능이 동작하기 위해 컴포넌트를 분리하여 관리
Bulb 컴포넌트
import { useState } from "react";
const Bulb = () => {
const [light, setLight] = useState("OFF");
return (
<div>
{light === "ON" ? (
<h1 style={{ backgroundColor: "orange" }}>ON</h1>
) : (
<h1 style={{ backgroundColor: "gray" }}>OFF</h1>
)}
<button
onClick={() => {
setLight(light === "ON" ? "OFF" : "ON");
}}
>
{light === "ON" ? "끄기" : "켜기"}
</button>
</div>
);
};
export default Bulb;
Counter 컴포넌트
import { useState } from "react";
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button
onClick={() => {
setCount(count + 1);
}}
>
+
</button>
</div>
);
};
export default Counter;
App 컴포넌트
Bulb, Counter 컴포넌트 추가
import "./App.css";
import Bulb from "./components/Bulb";
import Counter from "./components/Counter";
function App() {
return (
<>
<Bulb />
<Counter />
</>
);
}
export default App;