2024-03-11.md

๐Ÿก

DIL: ๋ชจ๋˜ ๋ฆฌ์•กํŠธ ๋”ฅ ๋‹ค์ด๋ธŒ, 2์ฃผ์ฐจ-1

์Šคํ„ฐ๋””: ์›”๊ฐ„ CS, https://github.com/monthly-cs/2024-03-modern-react-deep-dive
์˜ค๋Š˜ ์ง„ํ–‰: ๊ฐœ์ธ๊ณต๋ถ€


DIL-week2-1_2024-03-11

| DIL ์ฃผ์ฐจ | ๋ฒ”์œ„ | ๋‚ด์šฉ | ์˜ค๋Š˜์ฐจ ์ง„๋„ | | -------- | ------ | ------------------------------- | ----------- | | 2์ฃผ์ฐจ | 3, 5์žฅ | ๋ฆฌ์•กํŠธ ํ›…๊ณผ ์ƒํƒœ๊ด€๋ฆฌ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ | 189~194p |

์˜ค๋Š˜ ์ฝ์€ ๋‚ด์šฉ์„ markdown์œผ๋กœ ๊ฐ„๋‹จํžˆ ๋ฉ”๋ชจ
์ฝ์€ ์‹œ๊ฐ„: 10์‹œ๋ฐ˜~12์‹œ


React Hook ํŒŒํ—ค์น˜๊ธฐ

useState

const [state, setState] = useState(initialState); // initial state์ด ์—†๋‹ค๋ฉด ์ดˆ๊ธฐ๊ฐ’์€ undefined
  • ํ•จ์ˆ˜ ์ปดํฌ๋„ŒํŠธ ๋‚ด๋ถ€์—์„œ ์ƒํƒœ๋ฅผ ์ •์˜, ์ƒํƒœ๋ฅผ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ๋Š” ํ›…
  • ๋งค๋ฒˆ ๋ Œ๋”๋ง์ด ๋ฐœ์ƒ๋  ๋•Œ๋งˆ๋‹ค, ํ•จ์ˆ˜๋Š” ์ƒˆ๋กญ๊ฒŒ ์‹คํ–‰๋˜๊ณ , ์ƒˆ๋กญ๊ฒŒ ์‹คํ–‰๋˜๋Š” ํ•จ์ˆ˜์˜ ๊ฐ’์ด ์ดˆ๊ธฐํ™”๋œ๋‹ค.
    • ์ด๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด closure ์‚ฌ์šฉ
    • ์‹ค์ œ ๋ฆฌ์•กํŠธ ์ฝ”๋“œ์—์„œ๋Š” useReducer๋ฅผ ์ด์šฉ
      • ํ›…์˜ ๊ตฌํ˜„์ฒด ํƒ€๊ณ  ์˜ฌ๋ผ๊ฐ€๋ฉด? __SECRET_INTERNAL_DO_NOT_USE_OR_YOU_WILL_FIRED

=> MyReact์˜ useState์ด ๋ฐ˜ํ™˜ํ•˜๋Š” setState ๋‚ด์—์„œ ๋žœ๋”๋ง ๊ตฌํ˜„ํ•ด๋ณด๋ ค ํ–ˆ๋Š”๋ฐ ์‹คํŒจ

  • Uncaught RangeError: Maximum call stack size exceeded
    • MyReact.global ๊ฐ์ฒด์—์„œ index๋ฅผ ๊ด€๋ฆฌํ•ด์„œ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ์œผ๋กœ ๋ณด์ด๋Š”๋ฐ ์ ์  ๋ชฉ์ ์—์„œ ๋ฒ—์–ด๋‚˜๋Š” ๊ฒƒ ๊ฐ™์•„์„œ ์ค‘์ง€ -> ํ•™์Šต ์ง„๋„ ๋‹ค ๋‚˜๊ฐ„๋‹ด์— ์‹ฌ์‹ฌํ•˜๋ฉด ์žฌ๋„์ „
import React from "react";

export default function MyUseState() {
  return MyReact;
}

const MyReact = (() => {
  interface Global {
    states: any[];
  }

  const global: Global = {
    states: [],
  };

  let index = 0;

  type SetStateFunction = (value: any) => void;

  function useState(initState?: any): [any, SetStateFunction] {
    const currentIndex = index;

    if (typeof global.states[currentIndex] === "undefined") {
      global.states[currentIndex] =
        typeof initState !== "undefined" ? initState : null;
    }

    const currentState = global.states[currentIndex];

    const setState: SetStateFunction = (value) => {
      global.states[currentIndex] = value;
      forceUpdate();
    };

    index = index + 1;

    return [currentState, setState];
  }

  const [value, setValue] = useState(0);

  let render: React.FC<{ value: any }> = ({ value }) => (
    <section>
      <aside>
        <label>My UseState Hook</label>
        <div>{value}</div>
        <button onClick={() => setValue(value + 1)}>+</button>
      </aside>
    </section>
  );

  const forceUpdate = () => {
    render = (newValue) => render({ value: newValue });
    return render(value);
  };

  return render(value);
})();