03장 리액트혹 깊게 살펴보기

React Deep Dive

  • add table of contents

useState

  • 거슬러 올라가면 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED 라는 이름의 객체가 있다.
  • 이 객체는 공개 API가 아니며, React 내부에서만 사용한다.
  • 대충 클로저에 의존해 구현되어 있을 것이라는 추측

게으른 초기화

  • useState인자로 원시값이 아닌 함수 넘기는 것
//일반적인 useState사용
const [count, setCount] = useState(
  Number.parselnt(window.localStorage.getltem(cacheKey))
);
// 게으른 초기화
const [count, setCount] = useState(() => {
  // 함수
  Number.parselnt(window.localStorage.getltem(cacheKey));
});
  • use lazy intialization when 초깃값이 무겁거나 비싼 연산을 필요로 할 때
  • state 처음 만들어질 때만 사용됨. 리렌더링 될때는 무시됨!

  • ex:
    • localStorage나 sessionStorage에 대한 접근
    • map. fi1ter. find 같은 배열에 대한 접근
    • 초깃값 계산을 위해 함수 호출이 필요할 때 등

useEffect