[React] Hook (useState, useEffect)

이상헌·2021년 4월 18일
0

React

목록 보기
2/2
post-thumbnail

간략하게 Hook을 소개하자면 컴포넌트의 state를 쉽게 다룰 수 있게하는 기능이다.

useState

  • 인자
    생성되는 state 변수의 초기값
  • 반환 값
    state 변수와 변수의 setter를 배열로 반환한다.

생성되는 state 변수는 컴포넌트가 rendering될 때 한 번만 생성된다.

반환 받은 setter로 쌍이 되는 state 변수를 수정하며 이때마다 setState를 사용할 때 처럼 rerender해서 컴포넌트한테 넘겨준다.

import React, { useState } from 'react';

function Example() {
  // "count"라는 새 상태 변수를 선언합니다
  const [count, setCount] = useState(0);

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

useEffect

  • 인자
    첫 번째 인자로 함수를 받는다. (적용할 effect를 넘겨준다.)
    두 번째 인자로 배열을 받을 수 있다. (배열에 명시된 값이 수정될 때 effect를 적용한다.)

첫 번째 인자만 줄 때(componentDidMount, componentDidUpdate)

useEffect에 넘겨준 함수를 effect라고 부른다. useEffect는 컴포넌트가 렌더링 될 때마다 불리고 두 번째 인자가 없다면 effect를 실행한다.
불리는 시점은 렌더링이 완료되고 DOM이 업데이트된 후에 불린다.
componentDidMount와 componentDidUpdate, componentWillUnmount을 합쳐 놓은 느낌의 기능이다.

import React, { useState, useEffect } from 'react';

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

  // componentDidMount, componentDidUpdate와 같은 방식으로
  useEffect(() => {
    // 브라우저 API를 이용하여 문서 타이틀을 업데이트합니다.
    document.title = `You clicked ${count} times`;
  });

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

첫 번째 인자가 반환하는 함수(componentWillUnmount)

effect가 함수를 반환하도록 하면 componentWillUnmount가 불리는 시점에 effect의 반환 함수가 불린다.
다음과 같이 등록된 event listener를 지워줄(clean-up) 때 쓴다.

useEffect(() => {
	 document.addEventListener("mouseleave", handle);
	 return () => document.removeEventListener("mouseleave", handle);
	}, []);

두 번째 인자로 effect를 제한할 때

두 번째 인자로 배열을 넘겨줄 수 있다. 이렇게 두 번째 인자로 배열을 주면 배열에 명시된 값이 수정될 때만 effect를 실행한다. 배열이 비었을 경우 처음 렌더링할 때(componentDidMount)만 effect를 실행한다.

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // count가 바뀔 때만 effect를 재실행합니다.

참조:
https://ko.reactjs.org/docs/hooks-state.html
https://ko.reactjs.org/docs/hooks-effect.html

profile
배고픈 개발자 sayi입니다!

0개의 댓글