[react] 리액트 생명주기 메서드를 이용하여 상태를 업데이트하는 방법은 무엇인가요?

여기에서는 가장 일반적으로 사용되는 세 가지 생명주기 메서드를 통해 상태를 업데이트하는 방법을 살펴보겠습니다.

componentDidMount

컴포넌트가 DOM에 마운트된 후에 호출되는 componentDidMount 메서드를 활용하면 초기 상태를 설정하거나 외부 데이터를 불러와 상태를 업데이트할 수 있습니다. 예를 들어, 외부 API에서 데이터를 가져와 상태를 초기화할 수 있습니다.

class MyComponent extends React.Component {
  componentDidMount() {
    // 외부 데이터를 가져와 상태를 업데이트하는 예시
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => {
        this.setState({ data: data });
      });
  }
}

componentDidUpdate

컴포넌트의 상태나 속성(props)이 변경되면 호출되는 componentDidUpdate 메서드를 사용하여 상태를 업데이트할 수 있습니다. 이를 통해 이전 상태와 새 상태를 비교하거나 특정 조건에 따라 상태를 변경할 수 있습니다.

class MyComponent extends React.Component {
  componentDidUpdate(prevProps, prevState) {
    // 이전 상태와 새 상태를 비교하여 상태를 업데이트하는 예시
    if (this.props.data !== prevProps.data) {
      this.setState({ newData: this.props.data });
    }
  }
}

componentWillUnmount

컴포넌트가 제거되기 전에 호출되는 componentWillUnmount 메서드를 사용하여 컴포넌트가 제거되기 전에 정리 작업을 수행할 수 있습니다. 예를 들어, 타이머나 리소스를 해제할 때 활용할 수 있습니다.

class MyComponent extends React.Component {
  componentWillUnmount() {
    // 컴포넌트가 제거되기 전에 정리 작업을 수행하는 예시
    clearInterval(this.timer);
  }
}

이러한 생명주기 메서드를 활용하여 상태를 업데이트하는 것 외에도 다양한 방법이 있을 수 있으며, 프로젝트의 요구에 맞게 적절한 방법을 선택하여 활용할 수 있습니다.