Study/FrontEnd

리액트 훅(React Hook)이란?

ujam 2021. 9. 20. 21:26
728x90
반응형

Hook이란?

Hook은 react 버전 16.8부터 도입된 기능입니다.

함수형 컴포넌트에서 state와 Life cycle 기능을 연동할 수 있게 해줍니다.

useState, useEffect등의 기능을 사용하여 함수형 컴포넌트에서 할 수 없는 다양한 작업을 할 수 있게 해줍니다.

 

 

 

 

useState

 

class Test extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            name: "Ujam"
        };
    }

    render() {
        return <input value={name}
            onClick={(e) =>
                this.setState({
                    name: e.target.value
                })}
        />;
    }
}

기존 class의 state와 setState로 상태들을 관리했습니다.

 

 

 

import { useState } from 'react';

function Test() {
    const [name, setName] = useState("Ujam");

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

useState는 인자로 초기값을 받습니다.

name(현재 상태)와 setName(현재 상태 변경할 수 있는 함수)를 반환해줍니다.

useState를 사용하면 기존 classComponent로 구현한 코드보다 훨씬 간단하고 직관적인 코드가 됩니다.

 

 

 

 

 

useEffect

useEffect는 컴포넌트 안에서 렌더링 과정에서 작업들을 수행하도록 설정할 수 있습니다.

useEffect의 역할은 classComponent에서의 componentDidMount, componentDidUpdate, componentWillUnmount를 합친 형태로 볼 수 있습니다.

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

export function Data() {
  const [name, setName] = useState('');

  useEffect(() => {
    axios.get('url_address')
      .then((response) => { setName(response) });
  }, []);
  
  return()
}

 

 

 

 

 

 

 

항상 부족한 부분이나 피드백할 부분을 댓글로 남겨주시면 적극적으로 수용하여 수정하겠습니다.

728x90
반응형

'Study > FrontEnd' 카테고리의 다른 글

JavaScript란?  (0) 2021.10.05
리액트(React)란?  (0) 2021.09.18
타입스크립트(TypeScript)란?  (0) 2021.08.25