React에서는 컴포넌트를 작성할 때 클래스형 컴포넌트(Class Components)와 함수형 컴포넌트(Function components)
두 가지 방법이 있다.
React 16.8 버전에서 Hooks가 도입되면서 함수형 컴포넌트가 더 많이 사용되지만, 클래스형 컴포넌트도 여전히 존재하며 유지보수 할 필요가 있다.
render() 메서드를 사용하여 UI를 반환.
this.state, this.setState() 를 사용하여 산태를 관리한다.
생명주기 메서드(componentDidMount, componentDidUpdate, componentWillUnmout)를 제공한다.
상황에 따라 this의 바인딩이 필요 할 수 있다.
import React, { Component } from "react";
class ClassComponent extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<h1>클래스형 컴포넌트</h1>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>+1</button>
</div>
);
}
}
export default ClassComponent;
function 키워드를 사용하여 정의하거나 ES6 화살표 함수로 선언이 가능하다.
16.8 이후 Hooks를 사용하여 상태 및 생명주기 관리가 가능하다.
this 바인딩이 필요없어 코드가 더 간결해진다.
성능과 가독성이 뛰어나며 유지보수에 더 용이하다.
import React, { useState } from "react";
const FunctionComponent = () => {
const [count, setCount] = useState(0);
return (
<div>
<h1>함수형 컴포넌트</h1>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
);
};
export default FunctionComponent;
현재는 함수형 컴포넌트 사용이 일반적이며, React 개발팀도 Hooks 중심의 개발을 권장하고있다.
기존 코드의 유지보수 등을 위해 class형 컴포넌트의 개념 정도는 이해하고 있는 것이 좋을 것 같다.