TIL 14 | [React] Lifecycle

kim seung chan·2021년 8월 21일
0

Lifecycle에 대해 이해해보자 !

render, componentDidMount, componentDidUpdate, componentWillUnmount등의 함수는 class에서 제공하는 메서드이다. 컴포넌트를 만들때 class로 생성하면 위의 메서드를 이용할 수 있고, 컴포넌트의 lifecycle에 따라 각자의 메서드가 호출된다.

class Clock extends React.Component {

  constructor() {			// 1. 호출된다.
    super();

    this.state = {
      date: new Date()			// 2. 현재 시간으로 초기화
    };
  }

  componentDidMount() {			// 5. 함수 호출
    this.timerID = setInterval(		// 6. timer 추가
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {		// 8. DOM에서 Clock 컴포넌트 삭제 -> 함수 호출
    clearInterval(this.timerID);	// 9. timer stopped
  }

  tick() {
    this.setState({
      date: new Date()			// 7. this.state.date 값 변화(매초)
    });
  }

  render() {				// 3. render() 메소드 호출
    return (				// 4. DOM에 return 요소 추가
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,		// ReactDom.render()의 첫 인자
  document.getElementById('root')
);

lifecycle 메서드 추가

사용하던 리소스가 더 이상 필요가 없으면 없애주는 것이 필요하다. 컴포넌트가 mountingtimer를 추가하고 더 이상 화면에 unmounting 되는 순간 삭제해주어야 한다.

관련 메서드는 위에서 나온 componentDidMount, componentWillUnmount 이다.

출처

https://kyun2da.dev/react/%EB%A6%AC%EC%95%A1%ED%8A%B8-%EB%9D%BC%EC%9D%B4%ED%94%84%EC%82%AC%EC%9D%B4%ED%81%B4%EC%9D%98-%EC%9D%B4%ED%95%B4/

0개의 댓글