React - Lifecycle

군밤먹으면서코딩·2021년 6월 21일
0

React

목록 보기
2/8
post-thumbnail

render,componentDidMount,componentDidUpdate, componentWillUnmount 와 같은 함수들은 React.Component 클래스에서 제공하는 것들이다.
즉, class를 사용해 컴포넌트를 생성할 때 사용되는 함수들이다.

예제를 통한 이해

class Clock extends React.Component {

  constructor() {
    super();

    this.state = {
      date: new Date()
    };
  }

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

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

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);
  1. ReactDOM.render()의 첫 번째 인자에서 Clock을 넘겨줄 때, React는 Clock 컴포넌트의 constructor를 실행시킨다.

  2. constructor 내에 있는 super()는 extends한 React.Component의 메서드들을 사용하기 위해 반드시 붙여준다. 또한 this.state = {}에서 Clock의 초기상태 (여기서는 new Date)를 설정해 줄 수 있다.

  3. 이 후 render() 메서드가 호출된다.

  4. render() 메서드 내에 return이 실행되면, componentDidMount()메서드가 호출된다.

  5. component내 tick 함수가 매초 실행될 수 있도록 timer 추가

  6. 매초 브라우저가 tick 메서드를 호출하면서 this.state.date값이 변화.

  7. 이 때, componentDidUpdate()를 선언해주면 state가 변경될 때 호출되지만, 정의하지 않았으므로 rander()가 다시 호출되면서 바뀐 부분이 변경.

  8. DOM에서 Clock 컴포넌트가 삭제될 때 componentWillUnmount가 호출되고 timer도 함께 멈추게 된다.

0개의 댓글