[React] Closure와 Hook의 작동원리

Jay ·2022년 9월 4일
0

면접 질문

클로저란 무엇이며 어떻게/왜 사용하나?
리액트 Hook의 작동원리는?

클로저란?

클로저는 함수가 속한 렉시컬 스코프를 기억하여 함수가 렉시컬 스코프 밖에서 실행될 때에도 이 스코프에 접근할 수 있게 하는 기능을 뜻한다.
-Kyle Simpson-

useEffect 직접 구현해보기

  1. Usestate 예제
    Counter 컴포넌트가 다시 실행되어도 count의 값이 유지된다.
function Counter () {
  const [count, setCount] = useState(1);

  // 돔에서 직접 호출하기 위해 window(전역객체)에 할당
  window.increment = () => setCount(count + 1);

  return `
    <div>
      <strong>count: ${count} </strong>
      <button>증가</button>
    </div>
  `;
}
  1. customUsestate 직접 구현
const customUseState = (initVal) => {
  let innerState = initVal;
  const state = innerState;
  const setState = (newVal) => {
    innerState = newVal;
  };
  
  return [state, setState];
};

const [counter, setcounter] = customUseState(0);
console.log(counter)
setCounter(1)
console.log(counter);
const MyReact = (function () =>
  let state;

  return {
    render(Component) {
      const Comp = Component();
      Comp.render();
      return Comp;
    },

    useState(initialValue) {
      state ||= initialValue;

      const setState = (newValue) => {
        state = newValue;
      };

      return [state, setState];
    },
  };
})();

const Counter = () => {
  const [count, setCount] = MyReact.useState(0);

  return {
    click: () => setCount(count + 1),
    render: () => console.log('render:', { count }),
  };
};

let App;
App = MyReact.render(Counter); // render: { count: 0 }
App.click();
App = MyReact.render(Counter); // render: { count: 1 }

--> customUseState가 종료되면 innerState에 접근할 수 없다.
--> useState메소드 바깥쪽에 state를 저장.
-> useState함수 안에서 선언되는 상태들은 이 배열에 "순서대로" 저장됨 (Linked List)
--> 상태는 리액트 컴포넌트 바깥에 선언되어 있는 변수들이기 때문에 업데이트 한 이후에도 변수들에게 접근 가능.

Hook을 조건문, eventHandler(중첩함수)에서 호출하면 안되는 이유?

if(name !== ''){
  useEffect(function persistForm() {
    localStorage.setItem('formData', name);
  });
}

Hook은 컴포넌트 최상단에서만 호출되어야 한다.

References

https://yeoulcoding.me/149

profile
Jay입니다.

0개의 댓글