React

[React] Comonent 리랜더링 조건 / State로 Component 상태 관리

개발새발 2024. 8. 18. 15:52
반응형

리액트 컴포넌트는 아래 조건이 충족되면 Re-Rendering 된다.

 

1. 내 state 값이 변경 될 때

2. props 값이 변경 될 때

3. 부모 컴포넌트가 Re-Rendering 될 때

 

 

예) react의 useState hook을 이용하여 component의 상태를 관리

 

App Component에서

1) 버튼 클릭 시 on / off 상태 관리

2) 버튼 클릭 시 count 수 증가 상태 관리

 

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

function App() {
  // 컴보턴트 리렌더링 => 화면 바뀜
  const [count, setCount] = useState(0);
  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>
      <div>
        <h1>{count}</h1>
        <button
          onClick={() => {
            setCount(count + 1);
          }}
        >
          +
        </button>
      </div>
    </>
  );
}

export default App;

 

 

위와 같이 구현하면 내 state 값이 변경 될 때 component가 Re-Rendering특성을 가지고 있기 때문에

count만 변경해도가 on/off가 Re-Rendering된다.

React Developer Tools를 크롬에 설치하여 확인해보면 count버튼을 눌러도 on/off쪽이 다시 렌더링 된다. => 매우 효율적

 

 

 

따라서 아래와 같이 component를 나눠서 구조를 재설계하면 비효율적인 랜더링을 피할 수 있다.

 

App Component

import "./App.css";

import Bulb from "./components/Bulb";
import Counter from "./components/Counter";

function App() {
  return (
    <>
      <Bulb />
      <Counter />
    </>
  );
}

export default App;

 

 

Bulb Component

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 Component

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;

 

 

 

위와 같이 구현해 주면 각각 컴포넌트가 독립적으로 Re-Rendering 된다.

반응형