클래스, 함수 컴포넌트

이수정·2025년 10월 14일

JS_웹_풀스택

목록 보기
12/12

Class component & Functional Component

2.3장 클래스 컴포넌트와 함수 컴포넌트
초기 함수 컴포넌트 : 무상태 함수 컴포넌트 (정적 렌더링)

Class component

class SampleComponent extends React.Component {}

extends 구문을 통해 클래스 선언

  • React.Component
  • React.PureComponent
interface SampleProps {}
interface SampleState {}

class SampleComponent extends React.Component<SampleProps, SampleState> {
	//constructor : props 넘기고, state 기본값 설정
  public render() {}
}
  • constructor : 컴포넌트 초기화 되는 시점에 생성자 함수 호출
    - state 초기화
    • super() : 상위 컴포넌트 접근
  • props : like 함수에 인수 넣듯 컴포넌트에 특정 속성 전달
  • state : 클래스 컴포넌트 내부에서 관리하는 값(객체)
    -> 변화 있을 때 마다 리렌더링
  • 메서드
    - 일반 함수 호출 시 this가 전역객체 바인딩 -> bind 강제
this.handleClick =this.handleClick.bind(this)
//...

public render() {
  return (
    <button onClick={this.handleClick}></button>
  )
}
<button onClick={() => this.handleClick()}></button>

=> 매번 렌더링 일어날 때마다 새로운 함수 생성 -> 최적화 어려움

클래스 컴포넌트 생명주기 메서드

클래스 컴포넌트 : 생명주기 메서드에 의존

  • mount : 컴포넌트 생성 시점
  • update : 컴포넌트 내용 변경되는 시점
  • unmount : 컴포넌트가 더이상 존재하지 않는 시점

render()

  • 역할 : UI 렌더링
  • mount/update 과정에서 일어남
  • 항상 순수함수여야 함
    - 부수효과가 없어야 한다
    • 같은 props,state -> 같은 result
    • this.setState 호출 금지

componentDidMount()

  • mount되고 준비되는 즉시 실행
  • this.setState 가능 (사용자는 변경되는 것을 모름)
  • 성능 문제 있음
  • 역할 : API 호출 후 state 업데이트, DOM 의존적 작업등

componentDidUpdate()

  • update 일어난 후 실행
  • 역할 : state/porps 변화에 따라 DOM 업데이트
  • this.setState 가능
    - 적절한 조건문

componentWillUnmount()

  • unmount시 호출
  • 역할: 메모리 누수 막기 위한 클린업 함수 호출
  • this.setState 호출 불가능

shouldComponentUpdate()

  • 역할 : props나 state 변경으로 리렌더링을 막고싶다면
  • 특정 성능 최적화 상황에서만 고려
  • Component / PureComponent의 차이
    - component는 state 업데이트 되는 대로 렌더링
    • pureComponent는 state값이 변경되어야지 렌더링

0개의 댓글