[react] 생명주기 메서드를 사용하여 주기적인 특정 작업을 처리하는 방법은 무엇인가요?

예를 들어, 타이머를 설정하고 해제하는 작업을 생명주기 메서드를 사용하여 처리할 수 있습니다. 아래는 타이머를 설정하고 해제하는 예제 코드입니다.

import React, { Component } from 'react';

class Timer extends Component {
  constructor(props) {
    super(props);
    this.state = { seconds: 0 };
  }

  tick() {
    this.setState((prevState) => ({
      seconds: prevState.seconds + 1
    }));
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return (
      <div>
        Seconds: {this.state.seconds}
      </div>
    );
  }
}

export default Timer;

이 예제에서는 componentDidMount에서 setInterval을 사용하여 1초마다 tick 메서드가 호출되도록 설정하고, componentWillUnmount에서 clearInterval을 사용하여 타이머를 해제합니다.

이러한 방식으로 생명주기 메서드를 활용하여 컴포넌트의 마운트 및 언마운트 시에 필요한 작업을 처리할 수 있습니다.