👮 리액트 훅들

👻 useState

import { useState } from "react";

const [state, setState] = useState(initialState);

🤔 다음 코드가 동작하지 않는 이유는?

function Component() {
  let state = "hello";

  function handleButtonClick() {
    state = "hi";
  }

  return (
    <>
      <h1>{state}</h1>
      <button onClick={handleButtonClick}>hi</button>
    </>
  );
}

👀 useState 내부의 모습을 구현한 모습

실제 코드는 아님. 실제 코드는 useReducer를 사용해 구현돼 있음

const MyReact = function () {
  const global = {};
  let index = 0;

  function useState(initialState) {
    if (!global.states) {
      global.states = [];
    }

    const currentState = global.states[index] || initialState;
    global.states[index] = currentState;

    const setState = (function () {
      // 현재 index를 클로저로 가둬놔서 이후에도 계속해서 동일한 index에 접근할 수 있도록 함
      let currentIndex = index;
      return function (value) {
        global.states[currentIndex] = value;
      };
    })();

    index = index + 1;

    return [currentState, setState];
  }

  // 실제 useState를 사용하는 컴포넌트
  function Component() {
    const [value, setValue] = useState(0);
    // ...
  }
};

👀 게으른 초기화

// 바로 값을 집어넣음
const [count, setCount] = useState(
  Number.parseInt(window.localStorage.getItem(cacheKey))
);
// 함수를 실행해 값을 반환 -> 게으른 초기화
const [count, setCount] = useState(() =>
  Number.parseInt(window.localStorage.getItem(cacheKey))
);

👻 useEffect