โœ๐Ÿป [Code Camp_TIL] 14์ผ์ฐจ: state lifting

code_Jยท2023๋…„ 4์›” 4์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
21/41
post-thumbnail

state ๋Œ์–ด์˜ฌ๋ฆฌ๊ธฐ


react์˜ ๋ฐ์ดํ„ฐ ํ๋ฆ„์€ ๋‹จ๋ฐฉํ–ฅ์ด๋‹ค. ๋‹จ๋ฐฉํ–ฅ ๋ฐ์ดํ„ฐ ํ๋ฆ„์˜ ๊ฒฝ์šฐ์—๋Š” ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์ž์‹ ์ปดํฌ๋„ŒํŠธ์—๊ฒŒ๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋„˜๊ฒจ์ค„ ์ˆ˜ ์žˆ๋‹ค.

๋งŒ์•ฝ ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ ์•„๋ž˜์— ์ž์‹ ์ปดํฌ๋„ŒํŠธ1๊ณผ ์ž์‹ ์ปดํฌ๋„ŒํŠธ2๊ฐ€ ์žˆ๋‹ค๋ฉด, ์ž์‹ ์ปดํฌ๋„ŒํŠธ1์˜ state๋ฅผ ์ž์‹ ์ปดํฌ๋„ŒํŠธ2์—์„œ ๋ณด์—ฌ์ฃผ๋Š” ๊ฒƒ์€ ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค.


์ •๋ง ์ž์‹ ์ปดํฌ๋„ŒํŠธ1์˜ state๋ฅผ ์ž์‹ ์ปดํฌ๋„ŒํŠธ2์—์„œ๋„ ๋ณด์—ฌ์ค„ ์ˆ˜๋Š” ์—†๋Š” ๊ฑธ๊นŒ? ์ด๋Ÿด ๋•Œ ์“ธ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด ํ•œ ๊ฐ€์ง€ ์žˆ๋‹ค.

๋ฐ”๋กœ ์ž์‹ ์ปดํฌ๋„ŒํŠธ state์™€ setState๋ฅผ ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ๋กœ ๋Œ์–ด์˜ฌ๋ ค ์„ ์–ธํ•ด์ฃผ๋Š” ๊ฒƒ์ด๋‹ค! ๊ทธ๋ฆฌ๊ณ  props๋กœ state๋ฅผ ๋‚ด๋ ค์ค„ ๊ฒฝ์šฐ, ์ž์‹ ์ปดํฌ๋„ŒํŠธ 1,2์—์„œ ๋ชจ๋‘ state๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ์ด๊ฒƒ์„ state ๋Œ์–ด์˜ฌ๋ฆฌ๊ธฐ(state lifting)์ด๋ผ๊ณ  ํ•œ๋‹ค.

state lifting์€ ์ž์‹์˜ state๋ฅผ ๋ถ€๋ชจ์—๊ฒŒ ๋„˜๊ฒจ์ค€ ๊ฒƒ ๊ฐ™์€ ํšจ๊ณผ๋ฅผ ์ค€๋‹ค. ๊ฒฐ๊ณผ์ ์œผ๋กœ ์ž์‹ ์ปดํฌ๋„ŒํŠธ1์˜ state๋ฅผ ์ž์‹ ์ปดํฌ๋„ŒํŠธ2์—๋„ ๋„˜๊ฒจ์ค„ ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค. ์˜ˆ์‹œ๋ฅผ ๋ณด๋ฉด ๋” ์ž˜ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋‹ค.


// ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ 

import Child1 from "../../src/components/units/14-lifting-state-up/Child1";
import Child2 from "../../src/components/units/14-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}>์นด์šดํŠธ ์˜ฌ๋ฆฌ๊ธฐ</button>
    </div>
  );
}
// ์ž์‹ ์ปดํฌ๋„ŒํŠธ - Child2.tsx

export default function Child2(props) {
  return (
    <div>
      <div>์ž์‹ 2 ์นด์šดํŠธ: {props.count}</div>
      <button>์นด์šดํŠธ ์˜ฌ๋ฆฌ๊ธฐ</button>
    </div>
  );
}

๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ์— ์žˆ๋Š” state(count)๋ฅผ ์ž์‹ ์ปดํฌ๋„ŒํŠธ๋“ค์—๊ฒŒ props๋กœ ๋„˜๊ฒจ์ฃผ์—ˆ๋‹ค. ์—ฌ๊ธฐ์„œ ์ž์‹ ์ปดํฌ๋„ŒํŠธ1์— ์žˆ๋Š” ์นด์šดํŠธ ์˜ฌ๋ฆฌ๊ธฐ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด, ์ž์‹ ์ปดํฌ๋„ŒํŠธ2์— ์žˆ๋Š” count๋„ ๊ฐ™์ด ์ฆ๊ฐ€ํ•˜๊ฒŒ ๋œ๋‹ค!

์ด์ฒ˜๋Ÿผ state lifting์€ ์„œ๋กœ ๋‹ค๋ฅธ ์ž์‹ ์ปดํฌ๋„ŒํŠธ๋“ค๋ผ๋ฆฌ state๋ฅผ ๊ณต์œ ํ•˜๊ณ  ์‹ถ์„ ๋•Œ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.



profile
Web FE ๊ฐœ๋ฐœ์ž ์ทจ์ค€์ƒ

0๊ฐœ์˜ ๋Œ“๊ธ€