리액트의 컴포넌트들이 리렌더링 되는 상황 3가지
- 자신이 관리하는 state의 값이 변경되었을 때
- 자신이 제공받는 props의 값이 변경되었을 때
- 부모 컴포넌트가 리렌더링되면 자식 컴포넌트도 리렌더링 됨.
import "./App.css";
import { useState } from "react";
const Bulb = ({ light }) => {
console.log(light);
return (
<div>
{light === "ON" ? (
<h1 style={{ backgroundColor: "orange" }}>ON</h1>
) : (
<h1 style={{ backgroundColor: "gray" }}>OFF</h1>
)}
</div>
);
};
function App() {
const [count, setCount] = useState(0);
const [light, setLight] = useState("OFF");
return (
<>
<div>
<Bulb light={light} />
<button
onClick={() => {
setLight(light === "ON" ? "OFF" : "ON");
}}
>
{light === "ON" ? "끄기" : "켜기"}
</button>
</div>
<div>
<h1>{count}</h1>
<button
onClick={() => {
setCount(count + 1);
}}
>
+
</button>
</div>
</>
);
}
export default App;
분리
import "./App.css";
import Bulb from "./components/Bulb";
import Counter from "./components/Counter";
function App() {
return (
<>
<Bulb />
<Counter />
</>
);
}
export default App;
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;
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;