React와 Lifecycle Method

nona·2021년 1월 15일
0

React

목록 보기
4/7
post-thumbnail

Lifecycle method는 class component에서 옵션으로 쓸 수 있는 function으로, 특정한 포인트에 특정한 코드를 실행하기 위한 시스템이다.

화면에 (혹은 DOM에) 나타나서 -> re-render가 되고 -> 어느 순간에 화면에서 이 component가 사라지는 일련의 과정들을 Lifecycle이라고 한다.

componentDidMount

  • class component가 화면에 render되자마자 바로 딱 한번만 불러진다.
  • initial data loading (ex.API request)등을 넣을 수 있다. -> 이건 constructor에서도 할수 있지만, 공식적인 react문서에서는 constructor보다 componentDidMount에서 initial data-loading을 하는 것을 더 추천하고 있다. 기능상의 차이는 없지만, 더 깔끔한 코드정리를 위해서이다.

componentDidUpdate

  • setState로 컴포넌트가 업데이트될때마다 이 lifecycle method가 자동으로 불러진다.
  • 횟수에 제한없이 우리의 컴포넌트가 업데이트 될때마다 불러진다.
  • state/props이 바뀔때마다 필요한 다양한 data-loading을 넣어주면 좋다. (ex. 버튼, input, parent component로부터의 props 등)

componentWillUnmount

  • 어느순간에 우리가 component를 스크린에서 그만 보여주고 싶을때 사용한다.
  • Clean up을 위해서 사용한다고 생각하면 된다. 이전에는 google map등 non-react stuff 를 위해서 많이 사용되었지만, 리액트가 업데이트 된 이후로는 전보다 많이 사용하지 않는다

이외의 lifecycle method들:

shouldComponentUpdate
getDerivedStateFromProps
getSnapshotBeforeUpdate
가 있지만, 거의 사용되지 않고 특히 초보의 단계에서는 맨 위의 세가지에 집중하는게 좋다

예시 (geo location 이용)

class App extends React.Component {
  state = { lat: null, errorMessage: '' };
  //이거 constructor 메소드 코드와 같은것임. barbel을 이용한거

  componentDidMount() {
    window.navigator.geolocation.getCurrentPosition(
      position => this.setState({ lat: position.coords.latitude }),
      err => this.setState({ errorMessage: err.message })
    );
  }

  render () {
    return (
      <div className="border red">
        {this.renderContent()}
      </div>
    )
  };  
};

ReactDom.render(
  <App/>, document.querySelector('#root')
);

0개의 댓글