그동안 개발하면서 쉬운 사용성 때문에 주로 함수형 컴포넌트을 사용해왔었는데 문득 함수형 컴포넌트만을 사용해도 괜찮을까? 하는 의문점이 들었다.
import React from "react";
class MyComponent extends React.Component {
// constructor에서 props를 넘겨주고 state의 기본값을 설정한다.
private constructor(props) {
super(props);
this.state = {
count: 0,
isLimited: false,
};
}
// render 내부에서 쓰일 함수를 선언한다.
private handleClick = () => {
const newValue = this.state.count + 1;
this.setState({ count: newValue, isLimited: newValue >= 10 });
};
// render에서 이 컴포넌트가 렌더링할 내용을 정의한다.
public render() {
// props와 state 값을 this, 즉 해당 클래스에서 꺼낸다.
const {
props: { required, text },
state: { count, isLimited },
} = this;
return (
<h2>
Sample Component
<div>{required ? "필수" : "필수 아님"}</div>
<div>문자 : {text}</div>
<div>count : {count}</div>
<button onClick={this.handleClick} disabled={isLimited}>
증가
</button>
</h2>
);
}
}
// constructor에서 this 바인드를 하는 방법
private constructor(props){
this.handleClick = this.handleClick.bind(this)
}
// 화살표 함수를 쓰는 방법
private handleClick = () => {
const newValue = this.state.count + 1;
this.setState({ count: newValue, isLimited: newValue >= 10 });
};
// 렌더링 함수 내부에서 함수를 새롭게 만들어서 전달하는 방법
<button onClick={() => this.handleClick()}>증가</button>

// 클래스형 컴포넌트
import React, { Component } from 'react';
type SampleProps = {
required?: boolean;
text: string;
}
type SampleState = {
count: number;
isLimited: boolean;
}
class SampleComponent extends Component<SampleProps, SampleState> {
constructor(props: SampleProps) {
super(props);
this.state = {
count: 0,
isLimited: false
};
}
handleClick = () => {
const newValue = this.state.count + 1;
this.setState({
count: newValue,
isLimited: newValue >= 10
});
}
render() {
const { required, text } = this.props;
const { count, isLimited } = this.state;
return (
<h2>
Sample Component
<div>{required ? '필수' : '필수 아님'}</div>
<div>문자 : {text}</div>
<div>count : {count}</div>
<button onClick={this.handleClick} disabled={isLimited}>
증가
</button>
</h2>
);
}
}
export default SampleComponent;
//함수형 컴포넌트
import { useState } from 'react'
type SampleProps = }
required? : boolean
text: string
}
export function SampleComponent({ required, text } : SampleProps) {
const [count, setCount] = useState<number>(0)
const [isLimited, setLimited] = useState<boolean>(false)
function handleClick() {
const newValue = count + 1
setCount(newValue)
setIsLimited(newValue >= 10)
}
return (
<h2>
Sample Component
<div>{required ? '필수' : '필수 아님'}</div>
<div>문자 : {text}</div>
<div>count : {count}</div>
<button onClick={handleClick} disabled={isLimited}>
증가
</button>
</h2>
)
}
처음 함수 컴포넌트만 사용해도 괜찮은가 라는 질문에는 Yes라고 대답할 수 있을 것 같다. 하지만 숙련된 리액트 개발자가 되려면 그동안 리액트가 어떠한 고민을 통해 발전했는지 이해할 필요가 있다. 클래스 컴포넌트에 대해 배워둔다면 리액트를 매끄럽게 다루는 데에 큰 도움이 될 수 있을 것 같다.