React에서 Functional Components와 Class Components는 각각 다른 방식으로 컴포넌트를 선언하고 관리합니다. 이 두 가지 방식의 주요 차이점은 다음과 같습니다:
선언 방식
Class Components:
class
키워드를 사용하여 선언하며,React.Component
를 상속받아야 합니다.render()
메서드가 반드시 필요합니다.class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
Functional Components: JavaScript 함수로 선언되며, JSX를 반환합니다.
render()
메서드가 필요하지 않습니다.function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
State 관리
Class Components:
this.state
를 통해 상태를 초기화하고,this.setState()
를 사용하여 상태를 업데이트합니다.class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Increment </button> </div> ); } }
Functional Components:
useState
Hook을 사용하여 상태를 관리합니다.import { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
LifeCycle 메서드
Class Components: LifeCycle 메서드(
componentDidMount
,componentDidUpdate
,componentWillUnmount
등)를 직접 사용할 수 있습니다.class Clock extends React.Component { componentDidMount() { console.log('Clock mounted'); } render() { return <div>Current Time</div>; } }
Functional Components: LifeCycle 메서드 대신
useEffect
Hook을 사용하여 비슷한 기능을 구현할 수 있습니다.import { useEffect } from 'react'; function Clock() { useEffect(() => { console.log('Clock mounted'); }, []); return <div>Current Time</div>; }
메모리 사용량
- Class Components: 함수형 컴포넌트보다 메모리 사용량이 더 많습니다.
- Functional Components: 메모리 사용량이 적고, 선언이 간단합니다.
이벤트 핸들링
Class Components: 이벤트 핸들러를 선언할 때
this
를 사용해야 합니다.class Button extends React.Component { handleClick = () => { console.log('Button clicked'); }; render() { return <button onClick={this.handleClick}>Click</button>; } }
Functional Components: 이벤트 핸들러를 선언할 때
this
가 필요하지 않습니다.function Button() { const handleClick = () => { console.log('Button clicked'); }; return <button onClick={handleClick}>Click</button>; }
함수형 컴포넌트와 클래스형 컴포넌트의 성능 차이는 주로 메모리 사용량과 렌더링 성능에서 나타납니다.
메모리 사용량
- 클래스형 컴포넌트: 클래스형 컴포넌트는 인스턴스를 생성하기 때문에 각 인스턴스마다 메모리를 사용합니다. 이는 불필요한 메모리 할당으로 이어질 수 있습니다.
- 함수형 컴포넌트: 함수형 컴포넌트는 인스턴스를 생성하지 않기 때문에 메모리 사용량이 적습니다. 이는 메모리 효율성을 높이는 데 유리합니다.
렌더링 성능
- 클래스형 컴포넌트: 클래스형 컴포넌트는 인스턴스 생성 과정과 불필요한 메서드 호출로 인해 렌더링 성능이 상대적으로 떨어질 수 있습니다.
- 함수형 컴포넌트: 함수형 컴포넌트는 간결한 코드 구조와 Hook을 통해 상태 관리 및 사이드 이펙트를 효율적으로 처리할 수 있어 렌더링 성능이 더 우수합니다.
결론
함수형 컴포넌트는 메모리 사용량이 적고 렌더링 성능이 더 우수하여, 특히 대규모 애플리케이션에서 성능 최적화에 유리합니다. 반면, 클래스형 컴포넌트는 복잡한 상태 관리가 필요한 경우에 더 적합할 수 있습니다. 그러나 최근 React 개발에서는 함수형 컴포넌트와 Hook의 사용이 권장되고 있습니다.