컴포넌트는 UI를 구성하는 독립적이고 재사용 가능한 블록이다. 웹 페이지를 만들 때 헤더, 사이드바, 본문, 버튼 등을 각각 하나의 '블록'처럼 만들고, 이 블록들을 조립하여 전체 화면을 완성하는 방식이다.
React에서 컴포넌트를 선언하는 방식에는 크게 클래스형(Class)과 함수형(Functional) 두 가지가 있다.
과거 React에서 상태(State) 관리와 라이프사이클(Lifecycle) 기능을 사용하기 위해 필수적으로 사용했던 방식이다.
class 키워드를 사용하며, React.Component를 상속(extends) 받아야 한다.render() 메서드가 필요하다.this.state)와 라이프사이클 메서드(componentDidMount, componentDidUpdate 등)를 사용할 수 있다.import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
// State 초기화
this.state = {
count: 0
};
}
render() {
return (
<div>
<h1>카운트: {this.state.count}</h1>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
증가
</button>
</div>
);
}
}
export default Counter;
현재 React 개발의 표준이자 대세로 자리 잡은 방식이다.
=>) 문법을 사용하여 선언한다.import React, { useState } from 'react';
const Counter = () => {
// useState Hook을 통한 상태 관리
const [count, setCount] = useState(0);
return (
<div>
<h1>카운트: {count}</h1>
<button onClick={() => setCount(count + 1)}>
증가
</button>
</div>
);
};
export default Counter;
| 구분 | 클래스형 컴포넌트 (Class) | 함수형 컴포넌트 (Functional) |
|---|---|---|
| 선언 방식 | class 키워드, React.Component 상속 필요 | 일반 함수 또는 화살표 함수 사용 |
| 렌더링 | render() 메서드 필수 | return 문으로 바로 JSX 반환 |
| 상태(State) 관리 | this.state 와 this.setState 사용 | useState Hook 사용 |
| 라이프사이클 | componentDidMount 등의 라이프사이클 메서드 | useEffect Hook 하나로 통합 관리 |
| 코드 길이 / 가독성 | 길고 복잡함 (this 바인딩 등 주의 필요) | 짧고 간결함, 로직 파악이 쉬움 |