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

또한, setInterval이나 setTimeout과 같은 JavaScript 타이머 함수를 사용하여 주기적으로 작업을 수행할 수 있습니다. 이러한 타이머 함수는 componentDidMount에서 설정되고, componentWillUnmount에서 제거함으로써 메모리 누수를 방지할 수 있습니다.

아래는 componentDidMountcomponentWillUnmount을 사용하여 타이머 함수를 설정하고 제거하는 예시입니다.

import React, { Component } from 'react';

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

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

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

  tick() {
    this.setState({
      timer: this.state.timer + 1
    });
  }

  render() {
    return (
      <div>
        <h1>Timer: {this.state.timer}</h1>
      </div>
    );
  }
}

export default TimerComponent;

이 예시에서는 componentDidMount에서 1초마다 tick 메서드를 실행하는 타이머를 설정하고, componentWillUnmount에서 타이머를 제거함으로써 메모리 누수를 방지합니다. 이러한 방식으로 시간 관련 작업을 처리할 수 있습니다.

참고문헌: