React Hooks

조 은길·2021년 3월 29일
1

React

목록 보기
12/12
post-thumbnail

Hook 이전의 React

Props는 function과 class 둘 다에서 사용 가능!!
그러나, state는 오직 class에서 사용 가능했다. 더 정확하게는 state 값을 변경하는 작업은 class에서만 가능했다. 그래서, 이런 사용 원리가 작동했었다.

function : props 값을 화면에 표시해주는 용도로만 사용
class : 다양한 기능성을 필요로 할 때 사용

하지만, Hooks를 통해서, state가 function에서도 사용이 가능해졌다.
즉, class component에만 존재하던, "상태관리"와 "Life cycle"의 기능이 함수 컴포넌트에서도 사용이 가능해졌다.


Hook이란?

class없이 state를 사용할 수 있는 새로운 기능

그런데, function에서 state를 사용하려면, component들은 아래와 같이 선언되어야 한다.

function Example(props) {
  return <div />;
}

=> 근데, state를 사용하려면 setState()있어야지 않나용?? 없다!!
추가로, componentDidMount( ) 없다!!

대신 state와 React life cycle을 hook 할 수 있는 기능을 제공한다.

Hook = state + life cycle


Hook 의 장점

  • 함수만의 React Component 개발이 가능
  • 좀 더 쉬운 State Management ( 상태 관리 )

Hook 의 종류

=> React에는 다양한 종류의 Hook 있다.
하지만, 크게는

  • 1) "react에서 제공해주는 내장 hooks" 와
  • 2) "사용자가 직접 만드는 custom hooks"로 나눌 수 있다.

그리고 모든 hooks들은 이름이 다 use로 시작한다.
ex)
useState(), useEffect(), useReducer(), useMemo(), useCallback()...

학습 목표에서 선정한 2가지 Hook에 대해서만 중점적으로 알아보자!

1.State Hook : useState( )

=> state를 hook할 수 있는 기능이다.
=> react에서 상태 관리 할 때는 useState를 써라!!

기존에는 아래와 같이 class의 state와 setState로 상태를 관리했다면,

case1)

class Example extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     name: "좋은 길"
   };
 }
 
 render() {
 	return <input value={name} onClick={(e) => this.setState({ name : e.target.value })} />;
 }
}

=> state를 class 방식에서는 하나의 객체 안에 넣어야 했다.
=> 그러나, 밑의 functional 방식에서는 state를 만들 때마다, useState( )를 사용하면 된다. 다시 말해, 2개의 다른 변수를 저장하고 싶다면, useState( )를 2번 불러야 한다.

이제는 기존 class의 render() 단계에 해당되는 로직에 집중하면 된다.
그리고 state가 필요한 경우 useState를 사용하여 hook 합니다.

case 2)

import { useState } from 'react';

function Example() {
  const [name, setName] = useState("내가 초기값임");

  return <input value={name} onChange={(e) => setName(e.target.value)} />;
}

**useState는 인자로 초기값을 받고,
"현재 상태"(name)와 "현재 상태를 업데이트할 수 있는 함수"(setName) 를 반환해줍니다.

name을 this.state 그리고 setName이 this.setState()라고 생각하면 이해가 쉽다.**

function ExampleWithManyStates() {
 
 // 이렇게 여러 개의 state를 선언할 수 있다!
 
 const [age, setAge] = useState(42);
 const [fruit, setFruit] = useState('banana');
 const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
 
}

2. Effect Hook : useEffect( )

=> Lifecycle에서 마무리 단계 즉, rendering 이후에 처리되는 것들을 넣을 수 있다.
즉, 기존 React life cyle에 해당하는 로직들은 useEffect를 사용하여 hook할 수 있습니다.

case1) 기존에는 이런식으로 했다면,

class Data extends React.Component {
  constructor(props) {
    super(props);
    this.state = { item : null };
    this.setData = this.setData.bind(this);
  }

  componentDidMount() {
    API.getData()
      .then((response) => { this.setData(response) });
  }

  setData(data) {
    this.setState({ item: data });
  }
  
  render() {
    const isLoading = (this.state.item == null);
  	return { isLoading ? "Loading..."  : this.state.item }
  }
}

이제는 useEffect를 사용하여 다음과 같이 구현할 수 있다.

case2)

import { useState, useEffect } from 'react';

export function Data() {
  const [data, setData] = useState(null);

  useEffect(() => {
    API.getData()
      .then((response) => { setData(response) });
  }, []);
  
  const isLoading = (data == null);
  return { isLoading ? "Loading..."  : data }
}
  • useEffect는 React life cycle 중 어느 부분에 해당 하는가??
    => componentDidMount와 componentDidUpdate, componentWillUnmount를 합쳐놓은 것에 해당됩니다.

자료 출처 및 참고 자료

  • Using the State Hook

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

  • Using the Effect Hook

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

https://velog.io/@ichbinmin2/react-hooks

profile
좋은 길로만 가는 "조은길"입니다😁

0개의 댓글