728x90

클래스 컴포넌트(Class Components)와 함수형 컴포넌트(Functional Components)

들어가며

  • 리액트(React)는 기본적으로 클래스 컴포넌트(Class Components)함수형 컴포넌트(Functional Components) 2가지 유형의 컴포넌트를 제공한다.
  • 최신 리액트 버전에서는 함수형 컴포넌트훅스(Hooks)를 사용하는 것이 권장되며, 상태 관리 라이프사이클 이벤트 처리를 더 간단하게 할 수 있는 장점이 있다.
    • 그러나 이미 클래스 컴포넌트로 작성된 코드가 많다면, 따로 변경할 필요는 없다.
  • 클래스 컴포넌트함수형 컴포넌트에 대해 알아보자.

 

클래스 컴포넌트(Class Components)

  • ES6클래스 문법을 사용하여 생성된다.
  • @class@ 키워드를 사용하여 만들어지며, @React.Component@ 클래스를 확장한다.
  • @State@를 가질 수 있고, 라이프사이클 메서드(@componentDidMount@, @componentDidUpdate@, @componentWillUnmount@ 등)를 사용할 수 있다.
  • 기능이 많고 복잡한 컴포넌트를 만들기에 적합하다.
  • 예전의 리액트 버전에서 주로 사용되었으나, 최신 버전에서는 함수형 컴포넌트훅스(Hooks)를 활용한 함수형 컴포넌트가 더 인기를 얻고 있다.
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // ...
    };
  }

  componentDidMount() {
    // ...
  }

  render() {
    return (
      // 컴포넌트의 JSX 반환
    );
  }
}

 

함수형 컴포넌트(Functional Components)

  • 함수(Function)로 작성되며, 상태 관리를 위해 리액트 훅스(Hooks)를 사용할 수 있다.
  • 간단하고 명확하며, 성능상의 이점이 있을 수 있다.
  • 최근의 리액트 버전에서 함수형 컴포넌트훅스가 주로 사용된다.
  • 컴포넌트의 생명주기 메서드를 직접 사용할 수는 없지만, 훅스를 통해 비슷한 기능을 구현할 수 있다.
import React, { useState, useEffect } from 'react';

function MyComponent(props) {
  const [state, setState] = useState(initialState);

  useEffect(() => {
    // ...
  }, [dependencies]);

  return (
    // 컴포넌트의 JSX 반환
  );
}

 

 

예제 코드

App.jsx
  • 클래스 컴포넌트를 사용한 예제
import React from "react";
import ClassComponent from "./ClassComponent";
import FunctionalComponent from "./FunctionalComponent";

class App extends React.Component {
  render() {
    return <ClassComponent />;
  }
}

export default App;

 

ClassComponent.jsx
import React from "react";

class ClassComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 0
    };
    this.increase = this.increase.bind(this);
  }

  increase() {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div>
        <h1>{this.state.count}</h1>
        <button onClick={this.increase}>+</button>
      </div>
    );
  }
}

export default ClassComponent;

 

FunctionalComponent.jsx
import React, { useState } from "react";

function FunctionalComponent() {
  const [count, setCount] = useState(0);

  function increase() {
    setCount(count + 1);
  }

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={increase}>+</button>
    </div>
  );
}

export default FunctionalComponent;

 

참고 사이트

 

React Components

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

Components and Props – React

A JavaScript library for building user interfaces

legacy.reactjs.org

 

Hooks FAQ – React

A JavaScript library for building user interfaces

legacy.reactjs.org

 

728x90