[React] Function Component와 Class Component

J.·2024년 5월 15일

React

목록 보기
2/11
post-thumbnail

🔍 한눈에 알아보기

Function ComponentClass Component의 차이

Function ComponentClass Component
간결하고 가독성 높음길고 가독성 떨어짐
state 사용 x생성자에서 state 정의
Lifecycle에 대한 기능 구현 xsetState() 함수로 state 업데이트
Hook의 사용Lifecycle 함수 제공

1) Syntax와 구조

  • Function component는 더 심플하고 간결한 문법을 사용
  • Class component는 조금 더 복잡한 ES6 문법을 사용

2) State와 Lifecycle의 사용

  • Function component는 더 모듈화 되어있으며 재사용성이 높은 hook이라는 것을 사용해 state와 lifecyle을 관리
  • Class component는 this.state를 사용해 state를 관리하며 componentWillUnmount와 같은 lifecycle 함수를 사용

3) 사용 되는 곳

  • 새로 시작하는 프로젝트라면 간결하고 유연한 hook을 활용하는 function component를 사용
  • 이전에 생성된 프로젝트에서 class component를 아직 많이 사용함

📌Function Component

요즘에는 거의 무조건적으로 function component를 사용한다.

아래 코드는 Counter라는 function component의 예시이다.

import React, { useState } from 'react';

function Counter() {
    // 'count'라는 state 변수와 'setCount'라는 state 함수를 정의
    // 'count'의 초기 값을 0으로 설정
    const [count, setCount] = useState(0);

    return (
        <div>
            <h1>Counter: {count}</h1> {/* 현재 count를 출력 */}
            <button onClick={() => setCount(count + 1)}>더하기</button> {/* count를 더함 */}
            <button onClick={() => setCount(count - 1)}>빼기</button> {/* count를 뺌 */}
            <button onClick={() => setCount(0)}>초기화</button> {/* count를 0으로 초기화 시킴 */}
        </div>
    );
}

export default Counter;

위 코드를 참고해 Function component의 특징을 알아보자.

1) 심플하고 간결한 Syntax

위 코드에서 볼 수 있듯, Function component는 JavaScript 함수 처럼 작성한다.

JSX를 return하는 함수로 사용이 많이 되는데, 이는 매우 간결하며 가독성이 좋아 많이 기용된다.

2) Hook의 사용

Hook은 React 16.8에 도입된 기능인데, 이는 component가 state를 사용할 수 있게 만들어준다.

위 코드에서는 useState라는 hook을 사용해 count라는 state를 관리한다.

이전에는 function component가 state와 lifecycle을 관리 할 수 없었지만, hook의 도입으로 가능하게 됐다.

3) 성능

Function component는 비교적 가볍고 성능면에서도 뛰어나다.

4) React 권장

앞서 말했듯이, function component는 비교적 '트렌디' 하고 모던한 접근 방식을 제공하기 때문에

React에서도 공식적으로 function component의 사용을 권장한다.


📌Class Component

아래 코드는 위에서 보여준 코드와 동일하게 작동하지만 class component로 작성 된 코드이다.

import React from 'react';

class Counter extends React.Component {
    constructor(props) {
        super(props);
        // State initialization
        this.state = { count: 0 };
    }

    // Lifecycle method: componentDidMount
    componentDidMount() {
        console.log('Counter component mounted');
    }

    // Lifecycle method: componentDidUpdate
    componentDidUpdate() {
        console.log(`Component updated. New count: ${this.state.count}`);
    }

    // Lifecycle method: componentWillUnmount
    componentWillUnmount() {
        console.log('Component will unmount...');
    }

    // count 더하기
    increase = () => {
        this.setState({ count: this.state.count + 1 });
    }

    // count 빼기
    decrease = () => {
        this.setState({ count: this.state.count - 1 });
    }

    // count 초기화
    reset = () => {
        this.setState({ count: 0 });
    }

    render() {
        return (
            <div>
                <h1>Counter: {this.state.count}</h1>
                <button onClick={this.increase}>더하기</button>
                <button onClick={this.decrease}>빼기</button>
                <button onClick={this.reset}>초기화</button>
            </div>
        );
    }
}

export default Counter;

이렇게만 봐도 function component와 비교했을 때 복잡하고 가독성이 떨어지는 것을 알 수 있다.

두 코드를 비교하며 class component의 특징은 무엇이 있는지 알아보자.

1) 다양한 기능

Class component는 ES6 클래스를 사용하기 때문에 기능이 더 많고

생명주기를 관리 할 수 있는 내장 함수들이 존재한다.

2) State와 lifecycle 함수

Hook이 도입되기 전에 class component가 statelifecycle을 관리 할 수 있는 유일한 방법이였다.

Class component에서는 this.state를 활용해 state를 업데이트 할 수 있고

componentDidMountcomponentWillUnmount와 같은 lifecycle 함수를 통해 component의 생명주기를 관리 할 수 있다.

3) 길다...

Class component에서는 생성자와 같은 function component에서는 불필요한 boilerplate 코드가 많다.

그렇기 때문에 가독성이 떨어지고 코드가 길어질 수 있다.

profile
코린이 (코인 어린이 아니라 코딩 어린이임)

0개의 댓글