React 컴포넌트 라이프사이클 메서드 정리

배경

신입 개발자와 코드 리뷰를 하다가 componentWillMount에서 API 호출하는 코드를 발견했다. 이게 왜 문제인지 설명하려다 보니 라이프사이클 전체를 다시 정리할 필요를 느꼈다.

라이프사이클 순서

Mounting

  1. constructor()
  2. componentWillMount()
  3. render()
  4. componentDidMount()

Updating

  1. componentWillReceiveProps(nextProps)
  2. shouldComponentUpdate(nextProps, nextState)
  3. componentWillUpdate(nextProps, nextState)
  4. render()
  5. componentDidUpdate(prevProps, prevState)

Unmounting

  1. componentWillUnmount()

실제 사용 패턴

class UserProfile extends React.Component {
  componentDidMount() {
    // API 호출은 여기서
    fetch(`/api/users/${this.props.userId}`)
      .then(res => res.json())
      .then(data => this.setState({ user: data }));
  }

  componentWillUnmount() {
    // 타이머, 이벤트 리스너 정리
    clearInterval(this.timer);
  }

  shouldComponentUpdate(nextProps, nextState) {
    // 불필요한 렌더링 방지
    return nextProps.userId !== this.props.userId;
  }
}

주의사항

  • componentWillMount는 SSR에서도 호출되므로 API 호출 금지
  • componentDidMount는 DOM이 준비된 후이므로 여기서 외부 라이브러리 초기화
  • setState 호출 시 무한 루프 조심 (특히 componentDidUpdate)

결론

라이프사이클 메서드는 React의 핵심이다. 각 메서드가 언제 호출되는지 정확히 이해하면 버그를 줄일 수 있다. 팀 위키에도 공유했다.