State Lifting

Yeeeeeun_IT·2022년 8월 14일
0

state 끌어올리기

리액트의 데이터 흐름은 부모 컴포넌트에서 자식 컴포넌트로 전달하는
하향식(단방향)의 데이터 흐름을 가지고 있다.

단방향 데이터 흐름은 코드의 흐름을 알기 쉽기 때문에 코드를 수정하기에 용이하다.

하지만, 하위 컴포넌트의 state를 상위 컴포넌트에서 변경하는 것이 불가하다.
이때 자식 컴포넌트의 state와 setState를 부모 컴포넌트로 끌어올려 선언해주고
이를 props로 내려주면 자식 컴포넌트에서 사용 할 수 있다.

// 부모 컴포넌트 - index.tsx
import Child1 from "../../src/components/units/lifting-state-up/Child1";
import Child2 from "../../src/components/units/lifting-state-up/Child2";
import { useState } from "react";
export default function LiftingStateUpPage() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <Child1 count={count} setCount={setCount} />
      <div>=========================================</div>
      <Child2 count={count} />
    </div>
  );
}
// 자식 컴포넌트 - Child1.tsx
export default function Child1(props) {
  const onClickCountUp = () => {
    props.setCount((prev) => prev + 1);
  };
  return (
    <div>
      <div>자식 1 카운트: {props.count}</div>
      <button onClick={onClickCountUp}>카운트 UP</button>
    </div>
  );
}
// 자식 컴포넌트 - Child2.tsx
export default function Child2(props) {
  return (
    <div>
      <div>자식 2 카운트: {props.count}</div>
      <button>카운트 UP</button>
    </div>
  );
}
profile
🍎 The journey is the reward.

0개의 댓글