Skip to content

Component Lifecycle

Johnwook Choi edited this page Jun 6, 2016 · 2 revisions

render

render() method is required.

  • 이 method 가 실행되면, this.props 와 this.state 를 참조하여 생성한 child element 를 반환한다.
  • null 이나 false 를 return 할 수도 있다. 이 때는 어떤 것도 render 하지 않는다.
  • 이 method 는 component 의 state 를 변경하지 않는 pure function 이어야 한다.
    • 따라서 같은 input 에 대하여 항상 같은 결과를 return 해야 한다.
    • DOM 을 읽거나 쓰지 말아야하며, setTimeout 등 browser 와의 interaction 도 없어야 한다.
    • 만약 browser 와의 interaction 이 필요하면 componentDidMount() 등의 다른 method 에서 필요한 작업을 수행해라.

Lifecycle Methods

Mounting: componentWillMount

  • 첫 rendering 바로 전, client 와 server 에서 모두, 한번 실행된다.
  • 이 method 에서 setState 를 실행하면, render() method 는 update 된 state 를 사용한다.

Mounting: componentDidMount

  • 첫 rendering 바로 후, client 에서만 실행된다.
  • 이 phase 에서는 children 에 자유로운 접근이 가능하다.
  • child component 의 componentDidMount() method 는 parent 의 componentDidMount() method 실행 전에 실행된다.
  • setTimeout 이나 setInterval, AJAX call 을 수행하고 싶다면, 이 method 에서 수행하라.

Updating: componentWillReceiveProps

  • Component 가 new props 를 받을 때 실행된다.
  • Initial rendering 시에는 실행되지 않는다.
  • render() 가 실행되기 전, prop 을 변경하여 setState 를 하기 위해 이 method 를 사용할 수 있다.
componentWillReceiveProps: function(nextProps) {
  this.setState({
    likesIncreasing: nextProps.likeCount > this.props.likeCount
  });
}

Updating: shouldComponentUpdate

  • 새로운 props 나 새로운 state 가 전달되어 새로운 rendering 이 발생하기 전에 실행된다.
  • Initial rendering 이나 forceUpdate 를 사용했을 때는 실행되지 않는다.
  • 새로운 props 나 새로운 state 가 component update 를 필요로 하지 않는다고 확신할 때 사용할 수 있다.
shouldComponentUpdate: function(nextProps, nextState) {
  return nextProps.id !== this.props.id;
}
  • shouldComponentUpdate 가 false 를 return 하면, render() 는 실행되지 않는다.
  • componentWillUpdate 와 componentDidUpdate 도 실행되지 않는다.

Updating: componentWillUpdate

  • 새로운 props 나 새로운 state 가 전달되어 새로운 rendering 이 발생하기 전에 실행된다.
  • Initial rendering 시에는 실행되지 않는다.
  • 이 method 에서는 setState 를 통해 state 를 변경할 수 없다.

Updating: componentDidUpdate

  • Component 의 update 가 DOM 에 반영된 직후 실행된다.
  • Initial rendering 시에는 실행되지 않는다.
  • Component 가 update 된 후 DOM 을 변경할 때 사용할 수 있다.

Unmounting: componentWillUnmount

  • Component 가 DOM 에서 unmount 되기 직전 실행된다.
  • 필요한 cleanup 을 실행할 수 있다.
    • invalidating timers, cleaning up any DOM elements that were created in componentDidMount.