🔷 React

[React] State와 Props

코딩하세현 2025. 4. 9. 01:16
728x90
import './App.css';
import { useState } from 'react';

const Bulb = ({ light }) => {
  return (
    <div>
      {light === 'ON' ? (
        <h1 style={{ backgroundColor: 'orange' }}>ON</h1>
      ) : (
        <h1 style={{ backgroundColor: 'gray' }}>OFF</h1>
      )}
    </div>
  );
};

function App() {
  // state 생성
  // 기본 구조: const [state, setState] = useState(0);
  const [count, setCount] = useState(0);
  // 2. lightState의 값을 on으로 바꾸면 전구가 렌더링된다.
  const [light, setLight] = useState('OFF');

  return (
    <>
      <div>
        <Bulb light={light} />
        {/* 1. 켜기 버튼을 눌러  */}
        <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;

끄기 켜기 버튼을 눌러 lightState를 계속 바꾸면 Bulb 컴포넌트(const Bulb)가 계속 리렌더링되는 것이다. 

 bulb같은 자식 컴포넌트는 부모로부터 받는 props의 값이 바뀌면 리렌더링이 발생한다. 

📝 props는 (의 값은) const Bulb = ({여기 부분})

 

+1버튼을 눌렀는데 큰솔창에는 bulb 컴포넌트가 계속 리렌더링되는 것을 확인할 수 있다. 

왜 그런것일까? 

 리액트 컴포넌트는 리렌더링이 발생하는 3가지 상황이 있다. 

1. 자신이 관리하는 state의 값이 변경될 때

2. 자신이 제공받는 props의 값이 변경될 때

3. 부모 컴포넌트가 리렌더링되면 자식 컴포넌트도 리렌더링이 됨

 

자 다시 돌아와서 설명을 해보겠다.

+ 버튼을 누르면 app컴포넌트에서 count state선언한 부분의 useState 값이 계속 바뀐다. 

이걸 볼때 1번과 3번이 적용된다. 

하지만 bulb 컴포넌트는 count의 값과 아무런 상관이 없다.

이런 자식 컴포넌트들이 많아 지면 성능 저하 문제 발생! 

 

🤔 이런 문제를 방지하려면 어떻게 해야할까?

관련 없는 두개의 state를 하나의 컴포넌트로 몰아넣기 보다는 서로 다른 컴포넌트로 분리하는 것이 좋다 .

import './App.css';
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>
  );
};

const Counter = () => {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h1>{count}</h1>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        +
      </button>
    </div>
  );
};

function App() {
  // state 생성
  // 기본 구조: const [state, setState] = useState(0);
  // const [count, setCount] = useState(0);
  // 2. lightState의 값을 on으로 바꾸면 전구가 렌더링된다.
  // const [light, setLight] = useState('OFF');

  return (
    <>
      <Bulb />
      {/* 1. 켜기 버튼을 눌러  */}
      {/* <button
          onClick={() => {
            setLight(light === 'ON' ? 'OFF' : 'ON');
          }}
        >
          {light === 'ON' ? '끄기' : '켜기'}
        </button> */}

      <Counter />
    </>
  );
}

export default App;

이런식으로 코드를 정리해주면 불필요한 요소들이 리렌더링되지 않는다. 

 

각각의 컴포넌트를 src 컴포넌트 폴더 아래 저장해두면 훨씬 좋다. => 모듈화 작업

728x90