[TIL] React Hooks

Ha Young Do·2021년 5월 31일
0

React Hooks

Hook/Hooks는 class component 없이 state를 쓸 수 있게 해 주는 React 내장 함수이다. Function component 안에서 state 및 lifecycle 기능을 "연동 (hook into)"시켜 준다고 하여 Hook이라 불린다.

State Hook: useState

useState[상태 변수, 상태 갱신 함수] = useState(상태 초기값)의 형태로 쓴다.

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

위의 예시에서 state hook으로 정의한 state는 count이고, count의 초기값은 0이며, setCount()라는 method를 이용해 마치 setState()를 사용하듯 count의 값을 갱신해 줄 수 있다. count에 저장된 값을 사용하려면 일반 변수처럼 JSX 안에 직접 불러서 사용하면 된다.

Effect Hook: useEffect

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

프로그래밍에서 side effect란, 함수 외부에 영향을 주는 경우를 말한다. React로 설계된 앱에서는 데이터를 불러오기 위해 fetch를 쓰는 등 component 외부에 영향을 주고 받는 경우, 이를 side effect라 칭한다.
useEffect() method는 component에서 발생하는 side effect를 handling해 주는 함수로, 기본적으로 해당 component가 새로 render될 때마다 불린다. useEffect() 내부의 작업으로 state가 변경될 때마다 업데이트 되는 내용을 처리해 줄 수 있다.

https://reactjs.org/docs/hooks-overview.html

profile
Codestates Software Engineering Full IM 28th

0개의 댓글