2 분 소요

클래스 컴포넌트 (Class Component) : 생성자와 생명주기 메소드를 통한 상태와 생명주기 관리

import { Component } from 'react';

class MyClassComponent extends Component {
  constructor(props) {
    super(props);
    // 초기 상태 설정
    this.state = {
      count: 0
    };
  }

  componentDidMount() {
    // 컴포넌트가 마운트된 후 실행되는 코드
    console.log('Component mounted');
  }

  componentDidUpdate(prevProps, prevState) {
    // 상태 또는 속성이 업데이트된 후 실행되는 코드
    console.log('Component updated', prevState.count, '->', this.state.count);
  }

  componentWillUnmount() {
    // 컴포넌트가 언마운트되기 전 실행되는 코드
    console.log('Component will unmount');
  }

  handleIncrement = () => {
    // 상태 업데이트 예시
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.handleIncrement}>Increment</button>
      </div>
    );
  }
}

export default MyClassComponent;

생성자 (Constructor) : 메소드 내에서 컴포넌트 자체를 참조 → this

constructor(props) {
  super(props);
  console.log("constructor");
}
  • this.state : 컴포넌트의 상태를 저장 (setState 메소드를 사용하여 업데이트)
  • this.props : 컴포넌트에서 사용되는 속성에 접근

생명주기 메소드 (Lifecycle Methods) : 클래스 컴포넌트의 생명주기에 따라 메소드를 실행

클래스 컴포넌트의 생명주기 메소드가 실행되는 시점?

  • 마운트 (Mount) : 컴포넌트가 생성되는 시점
    • Constructor, getDerivedStateFromProps, render, componentDidMount
  • 업데이트 (Update) : 이미 생성된 컴포넌트의 내용이 변경되는 시점
    • getDerivedStateFromProps, shouldComponentUpdate, render, getSnapshotBeforeUpdate, componentDidUpdate
  • 언마운트 (Unmount) : 컴포넌트가 더 이상 존재하지 않는 시점
    • componentWillUnmount

render()

  • 컴포넌트가 UI를 렌더링하기 위해 사용 (마운트, 업데이트 과정에서 실행)
  • 리액트 클래스 컴포넌트의 유일한 필수 값으로 사용
  • 항상 순수해야 하며 부수 효과가 없어야 함 → render 내에서 this.setState를 호출하면 안됨

static getDerivedStateFromProps(props, state)

  • props에 가져온 값을 상태에 넣을 때, 상태나 props이 변화했을 때 실행
  • 정적 (static) 메서드이므로 this에 접근할 수 없음
  • 상태를 업데이트하기 위해 객체를 반환하거나, 아무것도 업데이트하지 않을 경우 null 반환
  • propsstate를 동기화할 때 주로 사용

componentDidMount()

  • 클래스 컴포넌트가 마운트된 이후, 즉 트리에 삽입된 후에 실행
  • 데이터 가져오기, 구독 설정, DOM 조작 등의 부수 효과를 초기화할 때 적합
  • API를 호출하고, 가져온 데이터로 ```state``를 업데이트할 때 주로 사용

shouldComponentUpdate(nextProps, nextState)

  • 클래스 컴포넌트가 리렌더링을 할지 안할지 결정
  • 불리언 값 반환 (기본값은 true)
  • 불필요한 렌더링을 방지하여 성능 최적화에 사용

getSnapshotBeforeUpdate(prevProps, prevState)

  • 클래스 컴포넌트 엄데이트 직전의 DOM 내의 특정 값을 반환하면, 그 다음의 componentDidUpdate 반환
  • 컴포넌트가 업데이트되기 직전에 DOM에서 특정 값을 캡처
  • 값을 반환하거나 null 반환 → 반환된 값은 componentDidUpdate에 매개변수로 전달
  • 업데이트가 적용되기 전에 DOM의 이전 상태를 알아야 할 때 유용

componentDidUpdate(prevProps, prevState, snapshot)

  • 컴포넌트 업데이트가 일어난 이후에 실행 (초기 렌더링에는 호출되지 않음)
  • 컴포넌트가 업데이트된 후에 DOM을 조작하는 데 사용될 수 있음
  • 이전 props, 이전 stategetSnapshotBeforeUpdate에서 반환된 스냅샷을 매개변수로 받음
  • props 변경에 따라 네트워크 요청을 수행하거나, state 변경에 따라 DOM을 업데이트할 때 자주 사용

componentWillUnmount()

  • 컴포넌트가 언마운트되거나 더 이상 사용되지 않기 직전에 실행
  • 타이머 무효화, 네트워크 요청 취소, 구독 해제 등의 정리 작업 수행에 적합
  • 메모리 누수를 방지하기 위해 컴포넌트가 더이상 필요하지 않은 리소스 정리

태그:

업데이트: