React

[React] component 기본 구조 / State Lifting

개발새발 2024. 9. 1. 15:54
반응형

리액트의 데이터(state등)는 부모 component에서 자식 component로 내려간다.

 

만약 형제 component끼리 상태를 공유하고 싶으면?

=> 부모 component로 statef를 올린다. (= State Lifting)

 

예)

아래와 같은 app을 만들어보면

 

 

두 개의 자식 컴포넌트가 count값을 알아야 하기 때문에 부모 컴포넌트인 App으로 state lifting을 해야한다.

 

 

 

App.jsx

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

function App() {
  const [count, setCount] = useState(0); // State Lifting

  const onClickButton = (value) => {
    setCount(count + value);
  };

  return (
    <div className="App">
      <h1>Simple Counter</h1>
      <section>
        <Viewer count={count} />
      </section>
      <section>
        <Controller onClickButton={onClickButton} />
      </section>
    </div>
  );
}

export default App;

 

Viewer.jsx

const Viewer = ({ count }) => {
  return (
    <div>
      <div>현재 카운트 :</div>
      <h1>{count}</h1>
    </div>
  );
};

export default Viewer;

 

Controller.jsx

const Controller = ({ onClickButton }) => {
  return (
    <div>
      <button
        onClick={() => {
          onClickButton(-1);
        }}
      >
        -1
      </button>
      <button
        onClick={() => {
          onClickButton(-10);
        }}
      >
        -10
      </button>
      <button
        onClick={() => {
          onClickButton(-100);
        }}
      >
        -100
      </button>
      <button
        onClick={() => {
          onClickButton(100);
        }}
      >
        +100
      </button>
      <button
        onClick={() => {
          onClickButton(10);
        }}
      >
        +10
      </button>
      <button
        onClick={() => {
          onClickButton(1);
        }}
      >
        +1
      </button>
    </div>
  );
};

export default Controller;
반응형