[React] State와 Props

AReum·2024년 10월 19일

React

목록 보기
8/53
post-thumbnail

리렌더링 되는 3가지 이유

  • state의 값이 변경될 때
  • 자신이 제공 받는 props의 값이 변경될 때
  • 부모 컴포넌트가 리렌더링될 때 자식 컴포넌트도 리렌더링된다.

App 컴포넌트에 모든 기능을 입력하면 켜기 끄기 기능을 했을 때, 카운트 기능도 같이 동작 되는 불편함이 발생한다.

→ 각각의 기능이 동작하기 위해 컴포넌트를 분리하여 관리

각각의 컴포넌트를 생성하여 관리하기

Bulb 컴포넌트

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 컴포넌트

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;

App 컴포넌트

Bulb, Counter 컴포넌트 추가

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

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

강의 출처:
https://www.inflearn.com/course/한입-리액트

profile
개발 관련 공부한 것을 기록합니다.🎈

0개의 댓글