본문 바로가기
Today I learned

React Hook

by soheemon 2020. 2. 8.

공식문서

 

Hook의 개요

React 16.8버전 에 새로 추가되었다. Hook을 이용하여 Class를 작성할 필요 없이 상태값과 여러  React의 기능을 사용할 수 있다.

  • Hook은 함수 컴포넌트에서 React state와 생명주기 기능을 "연동(hook into)"할 수 있게 해주는 함수이다.
  • Hook은 class 안에서 동작하지 않는다. 대신 class 없이 React를 사용 할 수 있게 해준다.

 

1) State Hook

//버튼을 클릭하면 값이 증가하는 카운터 예시

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>
  );
}

실행 결과

useState가 바로 Hook이다.

  • state는 컴포넌트가 다시 렌더링 되어도 값이 초기화 되지 않고 그대로 유지할것이다.
  • useState는 현재의 state값과 이 값을 업데이트 하는 함수를 쌍으로 제공한다.
  • useState의 호출 인자는 초기 state Value다

a) 여러 state변수 선언하기

하나의 컴포넌트 내에서 State Hook을 여러개 사용할 수도 있다.

function ExampleWithManyStates() {
  // 상태 변수를 여러 개 선언했습니다!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
  // ...
}

곁다리

1) 배열 구조 분해

2) ES5에서 함수 매개변수의 기본값 설정하기

function drawEs5Chart(options) {
	options = options === undefined ? {} : options;
    var size = option.size === undefined ? 'big' : options.size;
    var cords = options.cords === undefined ? { x: 0, y: 0} : optionse.cords;
    var radius = options.radius === undefined ? 25 : options.radius;
    
    //draw(size, cords, radius);
}

drawES5Chart({
	cords: { x: 18, y: 30},
    radius: 30
});

2) Effect Hook

React 컴포넌트 안에서 데이터를 가져오거나 구독하고, DOM을 조작하는 작업등 이런 모든 동작을 "side Effects"라고 한다. 왜냐하면 다른 컴포넌트에 영향을 줄 수 있고 렌더링 과정에서는 구현할 수 없는 작업이기 때문이다.

 

Effect Hook(useFeect)는 함수 컴포는트 내에서 이런 side effects를 수행할 수 있게 해준다.

React class의 componentDidMount나 componentDidUpdate, componentWillUnmount와 같은 목적으로 제공되지만, 하나의 API로 통합된 것이다.

 

//React가 DOM을 업데이트 한 후에 문서의 타이틀을 바꾸는 컴포넌트

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

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>
  );
}

useEffect를 사용하면 React는 DOM을 바꾼 후에 effect 함수를 실행할것이다.

Effects는 컴포넌트 안에 선언되어있기 때문에, props와 state에 접근할 수 있다.

React는 매 렌더링 이후에 effects를 실행한다. (최초 렌더링 포함)

 

a) Effect를 해제 할 필요가 있다면- 그러니까 더이상 렌더링 이후 effect 함수를 실행하기를 원치 않을 경우에는 해제하는 함수를 반환해주면 된다. (optional)

아래 예제에서는 친구의 접속상태를 구독하는 effect를 사용했고, 구독을 해지함으로써 Effect를 해제해준다.

function FriendStatusWithCounter(props) {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  const [isOnline, setIsOnline] = useState(null);
  useEffect(() => {
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }
  // ...

이 예시에서 컴포넌트가 unmount될 때 React는 CatAPI에서 구독을 해지할것이다. 또한 재 렌더링이 일어나 effect를 재 실행하기 전에도 마찬가지로 구독을 해지한다. (unmount될때 return하는 ArrowFunction을 실행하나보다.)

 

댓글