본문으로 바로가기

[REACT] State를 Props로 전달하기

category 나의 주니어 개발 일기/REACT 2025. 6. 26. 14:38
728x90
반응형
SMALL

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, setState] = useState(0);
  const [light, setLight] = useState("OFF");

  return (    
     <>
    <div>
      <Bulb light={light} />
        <button onClick={() =>{
        setLight(light === "OFF"?"ON":"OFF")
        }}
      >{light === "OFF"?"켜기":"끄기"}</button>
    </div>

    <div>
      <h1>{count}</h1>
      <button onClick={() =>{
        setState(count+1)
        }}
      >
        +
      </button>
    </div>
    </>

    );
  }


export default App;

react 컴포넌트 리렌더링 기준

1.자신이 관리하는 state의 값이 변경되었을 때

2.자신이 관리하는 props의 값이 변경되었을 때

3.부모 컴포넌트가 리렌더링 됬을 때, 자식도 리렌더링 된다.

위 코드에서 Bulb 컴포넌트와 상관 없는 count의 값을 변경했는데도 불구하고 Bulb 컴포넌트의 light 상태가 변경되는 상황이 발생한다.

이유는? 리렌더링 기준중에서 3번에 해당되기 때문이다.

App 컴포넌트는 자신의 갖고 있는 count 의 state가 변경되었기 때문에 리렌더링되고 Bulb는 App 컴포넌트의 자식이기 때문에 3번에 해당되어 같이 리렌더링 된다.


그래서 서로 상관 없는 것들은 분리해야지만 서로의 상태변화에 영향을 끼치지 않는다.

분리하자!

App.jsx

import "./App.css";

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

function App() {

  return (    
    <>
      <Bulb />
      <Counter />
    </>
    );
  }

export default App;

Bulb.jsx

import { useState } from "react";

const Bulb = ()=>{

  const [light, setLight] = useState("OFF");

  console.log(light);
  return (
        <div>
          {light === "ON" ? (
            <h1 style={{ backgroundColor: "orange"}}>ON</h1>
          ) : (
            <h1 style={{ backgroundColor: "gray"}}>OFF</h1>
          )}

          <button onClick={() =>{
            setLight(light === "OFF"?"ON":"OFF")
            }}
          >{light === "OFF"?"켜기":"끄기"}</button>
        </div>
  );
};

export default Bulb;

Counter.jsx

import { useState } from "react";

const Counter = () => {
  const [count, setState] = useState(0);

  return (
      <div>
          <h1>{count}</h1>
          <button onClick={() =>{
            setState(count+1)
            }}
          >
            +
          </button>
      </div>
  );
};

export default Counter;
728x90
반응형
LIST