React의 LifeCycle

2021. 6. 30. 17:27·FE/React
반응형

LifeCycle method는 React component의 생성부터 소멸까지 일련의 이벤트들이라고 할 수 있다. 리액트의 모든 이벤트는 lifecycle을 지난다. 

 

1. Mounting

2. Updating

3. Unmounting


1. Mounting - 컴포넌트가 생성될 때, 다음과 같은 순서대로 호출된다.

 

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

constructor()

- React component의 constructor()는 컴포넌트가 마운트되기 전에 호출된다. 보통 개체를 this.state에 할당하여 로컬 상태를 초기화하거나, 인스턴스에 이벤트 처리기 메소드를 바인딩할 때 사용한다. 그리고 constructor()안에는 setState()를 사용하면 안된다. 만약 local state를 사용하고 싶다면 this.state를 직접 할당해야한다.

- 자주 하는 실수: thi

constructor(props) {
  super(props);
  // Don't call this.setState() here!
  
  this.state = { counter: 0 };
  
  //prop을 state로 copy하지 말기! Don't do this!
  //this.state = { color: props.color };
  
  this.handleClick = this.handleClick.bind(this);
}

render()

- render 메소드는 lifecycle 메소드에서 가장 많이 쓰이는 메소드이다. 이는 클래스 컴포넌트에 필요한 유일한 메소드이디 때문이다. 또한 render 메소드는 반드시 pure한 상태여야 한다. 이는 어떠한 side-effects도 없어야 하고, 같은 input이 들어왔을 때 같은 output이 나와야 함을 의미한다. 그리고 render() 안에서 컴포넌트의 상태를 바꿀 수 없다. (따라서 setState()는 render()안에서 사용할 수 없음.)

 

class Hello extends Component{
   render(){
      return <div>Hello {this.props.name}</div>
   }
}

componentDidMount()

- componentDidMount()는 컴포넌트가 마운트된 후 즉시 호출된다. 이 때 setState()를 바로 호출할 수 있고, 이는 추가적인 렌더링을 발생시키지만 이는 브라우저가 화면을 업데이트하기 전에 발생한다. 하지만 이렇게 할 때는 성능 이슈가 생길 수 있기 때문에 주의해서 사용해야 한다. 따라서 constructor()에 state를 할당해놓는 것이 좋다.


 

2. Updating - prop, state의 변경으로 인해 발생, 이는 컴포넌트가 다시 렌더링될 때 다음 순서로 호출된다.

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

componentDidUpdate()

componentDidUpdate(prevProps, prevState, snapshot)

- componentDidUpdate()는 업데이트가 발생하면 즉시 호출된다. 이 메소드는 처음 render를 할 때는 호출되지 않는다. 

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

- componentDidUpdate()안에 바로 setState()를 사용하지 말고 위와 같이 사용하도록 한다. 그렇지 않으면 무한 루프에 빠지게 될 것이다. 또한 이는 유저에게는 보이지 않지만 성능에는 영향을 줄 수 있는 불필요한 re-rendering을 발생시킬 수 있다.


3. Unmounting - 컴포넌트가 DOM에서 사라질 때 호출된다.

  • componentWillUnmount()

 

componentWillUnmount()

- componentWillUnmount()는 컴포넌트가 언마운트 되거나 파괴되기 직전에 호출된다. 타이머 무효화, 네트워크 요청 취소 등의 작업을 할 때 사용하며, 컴포넌트가 다시 렌더링되지 않기 때문에 componentWillUnmount()안에서는 setState()를 호출하지 않도록 주의한다.

componentWillUnmount() {
 window.removeEventListener('resize', this.resizeListener)
}

 

반응형

'FE > React' 카테고리의 다른 글

[React] Storybook 사용해보기  (0) 2022.12.02
React Infinite Carousel 만들기(TS)  (1) 2022.11.24
React 스톱워치 구현하기(TS)  (0) 2022.11.17
React 다크 모드 구현하기(with Recoil, SCSS)  (0) 2022.11.06
React 프로젝트에 i18n으로 다국어 지원하기  (0) 2022.10.31
'FE/React' 카테고리의 다른 글
  • React Infinite Carousel 만들기(TS)
  • React 스톱워치 구현하기(TS)
  • React 다크 모드 구현하기(with Recoil, SCSS)
  • React 프로젝트에 i18n으로 다국어 지원하기
SH_Roh
SH_Roh
  • SH_Roh
    혼자공부끄적끄적
    SH_Roh
  • 전체
    오늘
    어제
    • 분류 전체보기 (159)
      • FE (39)
        • HTML, CSS (3)
        • Javascript (17)
        • React (11)
        • Next.js (4)
      • Network (1)
      • DevOps (4)
      • Git (1)
      • Trouble Shooting (24)
      • Algorithm (41)
        • Python (2)
        • Data Structure, Algorithm (7)
        • Problem Solving (31)
      • Education (23)
        • Elice AI Track (4)
        • Wanted Pre-Onboarding FE Co.. (19)
      • TIL (25)
      • Etc. (1)
        • 회고 (1)
        • 그냥저냥 (0)
  • 링크

    • Github
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
SH_Roh
React의 LifeCycle
상단으로

티스토리툴바