Life Cycle Methods
클래스 컴포넌트의 라이프 사이클(Life Cycle) 메서드
라이프 사이클
생명은 시간의 흐름에 따라 시시각각 변화합니다. 예를 들어 닭의 "생명 주기"를 그려보면 아래 이미지와 같습니다. 생명은 탄생 전/후, 성장(업데이트) 전/후, 죽음 전/후로 흘러갑니다.

라이프 사이클 메서드
마찬가지로 컴포넌트는 또한 프로세스의 특정 시간에 코드를 실행하는 다양한 라이프 사이클 훅이 제공됩니다. 컴포넌트의 라이프 사이클을 크게 나눠보면 다음의 3단계로 진행됩니다.
단계
설명
마운트 (Mount)
컴포넌트 생성
업데이트 (Update)
컴포넌트 갱신
언 마운트 (Unmount)
컴포넌트 제거
컴포넌트의 라이프 사이클 훅에 대한 이해를 돕기 위해 아래 라이프 사이클 다이어그램을 참고합니다.
▀ 일반적인 라이프 사이클 다이어그램

▀ 보다 상세한 라이프 사이클 다이어그램

마운트
컴포넌트 인스턴스를 만들고 DOM에 마운트 될 때까지의 흐름은 다음 순서대로 메서드가 실행됩니다.
라이프 사이클 메서드
설명
컴포넌트 생성 시점에 호출
static getDerivedStateFromProps
전달된 상태 및 속성을 가져와 설정하는 시점에 호출
컴포넌트 렌더링 시점에 호출
DOM에 마운트 된 이후 시점에 호출
class LifeCycleMethods extends Component {
// 1.1 컴포넌트 생성
constructor(props) {
super(props)
console.log('컴포넌트 생성')
}
// 1.2 전달된 속성, 상태를 가져와 설정
static getDerivedStateFromProps(props, state) {
console.log('전달된 속성 및 상태를 가져와 설정')
}
// 1.3 컴포넌트 렌더링
render() {
console.log('컴포넌트 렌더링')
return <div />
}
// 1.4 컴포넌트 마운팅 됨
componentDidMount() {
console.log('컴포넌트 마운팅 됨')
}
}
componentWillMount는 더 이상 사용하지 않는 것이 좋습니다. (React v17 까지만 지원 예정)
업데이트
컴포넌트 props
, state
가 변경되면 업데이트 됩니다. 업데이트 과정에서 실행되는 메서드는 다음과 같습니다.
라이프 사이클 메서드
설명
static getDerivedStateFromProps
전달된 상태 및 속성을 가져와 설정하는 시점에 호출 (업데이트)
컴포넌트 업데이트 예정 시점에 호출 (업데이트 진행 여부 결정)
컴포넌트 렌더링 (업데이트)
컴포넌트 업데이트 전 스냅샷 가져오는 시점에 호출
컴포넌트 업데이트 이후 시점에 호출
class LifeCycleMethods extends Component {
// 2.1 속성, 상태 설정
static getDerivedStateFromProps(props, state) {
console.log('(업데이트) 전달된 속성 및 상태를 가져와 설정')
return null
}
// 2.2 업데이트 할 예정
shouldComponentUpdate(nextProps, nextState) {
console.log('성능 최적화 용도로 사용 됨')
return true // false를 반환할 경우 컴포넌트 렌더링이 취소
}
// 2.3 렌더링
render() {
console.log('(업데이트) 렌더링')
return <div />
}
// 2.4 DOM에 커밋되기 전
getSnapshotBeforeUpdate(nextProps, nextState) {
console.log('DOM에 커밋되기 전 스냅샷 가져오기')
return null
}
// 2.5 업데이트 됨
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('업데이트 됨')
}
}
componentWillUpdate, componentWillReceiveProps는 더 이상 사용하지 않아야 합니다.
언 마운트
컴포넌트가 DOM에서 제거되기 직전 실행되는 메서드입니다.
라이프 사이클 메서드
설명
컴포넌트 제거 예정 시점에 호출
class LifeCycleMethod extends Component {
// 3.1 DOM에서 언 마운트 되어 제거되기 직전에 실행
componentWillUnmount() {
console.log('DOM에서 언 마운트 되어 제거되기 직전에 실행 됨')
}
}
오류 처리
컴포넌트 렌더링, 라이프 사이클 훅이 실행될 때 오류가 발생한 경우 호출됩니다.
getDerivedStateFromError 메서드는 자식 컴포넌트에서 오류가 발생되면 이를 감지하여 컴포넌트의 state.hasError 상태를 업데이트 합니다. render 메서드는 업데이트 된 hasError 값을 확인 조건 처리하여 오류가 발생한 경우와 그렇지 않은 경우를 나눠 렌더링 합니다.
class ErrorBoundary extends Component {
state = { hasError: null }
// 자식 컴포넌트의 오류를 throw한 후 실행
static getDerivedStateFromError(error) {
// throw된 오류가 감지되면, hasError 상태 값을 true 처리
return { hasError: error }
}
render() {
// 오류 발생 시, 오류 컴포넌트 렌더링
if (this.state.hasError) {
return <ErrorDisplay />
}
// 오류가 발생하지 않은 경우 자식 노드 렌더링
return this.props.children
}
}
componentDidCatch 메서드는 자식 컴포넌트 오류가 발생된 이후 실행됩니다. error, info 2개의 매개변수가 전달되며 info는 어떤 컴포넌트가 오류를 발생시켰는 지에 대한 정보를 가진 componentStack 속성을 가진 객체입니다.
class ErrorBoundary extends Component {
state = { hasError: false }
static getDerivedStateFromError(error) {
return { hasError: error }
}
// 자식 컴포넌트의 오류를 throw한 후 실행
componentDidCatch(error, info) {
// info 매개변수:
// 어떤 컴포넌트가 오류를 발생시켰는지에 대한 정보를 가진 componentStack 속성을 가진 객체
// Example "componentStack":
// in ComponentThatThrows (created by App)
// in ErrorBoundary (created by App)
// in div (created by App)
// in App
logComponentStackToService(info.componentStack)
}
render() {
if (this.state.hasError) {
return <ErrorDisplay />
}
return this.props.children
}
}
Last updated
Was this helpful?