State와 Props

오현진·2024년 6월 26일

React

목록 보기
2/3

리액트의 컴포넌트들이 리렌더링 되는 상황 3가지

  1. 자신이 관리하는 state의 값이 변경되었을 때
  2. 자신이 제공받는 props의 값이 변경되었을 때
  3. 부모 컴포넌트가 리렌더링되면 자식 컴포넌트도 리렌더링 됨.
// App.jsx

import "./App.css";
import { useState } from "react";

// 자식 컴포넌트
const Bulb = ({ light }) => {
  // 버튼을 눌러서 앱 컴포넌트의 light State를 계속 바꿔주면, Bulb 컴포넌트가 계속 리렌더링됨.
  // 자식 컴포넌트들은 부모로부터 받은 props 값이 바뀌게 되면, 리렌더링이 발생함.
  // 리액트 컴포넌트들은 자신이 가진 State가 변경되지 않아도, 부모로부터 받는 props 값이 변경되면, 다시 리렌더링된다.
  console.log(light);
  // 또한 부모 컴포넌트에서 + 버튼을 눌러 count state 값이 변경되었을 때 리렌더링이 되므로, 자식 컴포넌트인 Bulb도 리렌더링된다.
  // 그래서 관련 없는 두 개의 state가 있다면 분리해주는게 좋다.
  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;

분리

// App.jsx

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;

0개의 댓글