어쩌다 알게 된 ƪ(•̃͡•̃͡ ƪ

클래스 컴포넌트 / 함수형 컴포넌트 본문

개발/🟦 React

클래스 컴포넌트 / 함수형 컴포넌트

비니_ 2025. 9. 3. 13:05
728x90

 

 

1️⃣ 클래스 컴포넌트

class WorkingSchduleDraggable extends Component {
  ...
}

 

  • React.Component를 상속해서 만듦
  • 장점:
    1. 생명주기 메서드 사용 가능
      • componentDidMount, componentWillUnmount, shouldComponentUpdate 등
    2. state 관리 가능 (this.state)
    3. 클래스 내부에서 메서드 참조 시 this 사용 가능
  • 단점:
    • 코드가 길어질 수 있음
    • 요즘 React에서는 함수 컴포넌트 + Hooks가 더 많이 사용됨

2️⃣ 함수 컴포넌트

function WorkingSchduleDraggable(props) {
  ...
}

 

 

  • 단순 함수로 컴포넌트 정의
  • 장점:
    1. Hooks 사용 가능 (useState, useEffect, useRef)
    2. 코드가 간결하고 이해하기 쉬움
    3. 요즘 React 공식 권장 스타일
  • 단점:
    • 클래스 생명주기 메서드(componentDidMount) 대신 useEffect 사용해야 함
    • this 없음 → 함수 안에서 state, ref, 메서드 참조 방식이 다름

 

🔹 차이 정리

구분 클래스 컴포넌트 함수 컴포넌트
state this.state / this.setState useState
생명주기 componentDidMount, componentWillUnmount 등 useEffect
ref createRef() / this.ref useRef()
this 사용 가능 사용 불가
코드 길이 비교적 길음 간결
최신 트렌드 레거시 프로젝트에서 자주 사용 현재는 함수 컴포넌트 + Hooks 권장

 

 

 

728x90
Comments