[React] class And function component

Chipmunk_jeong·2021년 5월 19일
0

TIL

목록 보기
47/62
post-thumbnail

리액트는 컴포넌트들이다

컴포넌트를 만들기 위해서는 class를 통해서 만들수도 있고,
함수로도 만들 수 있다.

class는 react의 Component를 상속받아 만들 수 있고,
함수는 일반 function키워드를 통하여 만들 수 있다.

// class Component
import React, {Component} from 'react';

class Button extends Componenet {
  state = {
    likeNumber: 0,
  };

  render() {
    return (
      <button>{this.state.likeNumber}</button>
    );
  };
}

export default Button;


// function Component
function Button(props) {
  return <button>{props.number}</button>
}

컴포넌트 내에서 상태(state)가 있고, 그 상태에 따라서 컴포넌트가 업데이트가 되어야한다면, class컴포넌트를 사용하면 되고,
컴포넌트 내에서 상태(state)가 없으며, 정적인 컴포넌트는 function 컴포넌트를 사용하면 된다.
(react hook을 사용하면 함수 컴포넌트에서도 클래스처럼 life cycle과 state를 사용할 수 있다)

class Componenet를 이용하면 다 할수있는데 왜 react hook?

  1. class개념이 어려워서
  2. this 키워드의 생략 & binding issue
  3. 함수형 프로그래밍을 이용히가 위해
  4. 좀더 간략한 문법
  5. class보다 가벼움
profile
Web Developer

0개의 댓글