Post

React 컴포넌트 생명 주기 함수(Lifecycle Methods) 이해하기

React 컴포넌트 생명 주기 함수(Lifecycle Methods) 이해하기

React 컴포넌트는 특정 시점에서 자동으로 호출되는 일련의 생명 주기 함수(Lifecycle Methods)를 가지고 있습니다. 이 함수들은 컴포넌트가 생성, 업데이트, 소멸되는 과정에서 특정 작업을 수행할 수 있게 해줍니다. 생명 주기 함수는 크게 세 가지로 나눌 수 있습니다: 생성, 업데이트, 소멸. 각 단계에서 호출되는 함수와 그 순서를 알아보겠습니다.

생성: 컴포넌트의 인스턴스 생성

컴포넌트가 처음 생성되고 DOM에 삽입될 때 순서대로 호출되는 생명 주기 함수들입니다.

  1. constructor()
    1
    2
    
    컴포넌트의 초기 상태를 설정하고 인스턴스를 초기화합니다.
    보통 상태(state)를 초기화하거나 인스턴스 변수 설정에 사용됩니다.
    
  2. getDerivedStateFromProps(props, state)
    1
    2
    
    주어진 props에서 state를 파생할 때 사용됩니다.
    정적 메서드로, 컴포넌트가 마운트되기 전에 호출됩니다.
    
  3. render()
    1
    2
    
    JSX를 반환하여 DOM 구조를 정의합니다.
    순수 함수로, state나 props의 변화를 기반으로 UI를 그립니다.
    
  4. componentDidMount()
    1
    2
    
    컴포넌트가 처음 DOM에 렌더링된 직후에 호출됩니다.
    데이터 가져오기, DOM 조작 등의 초기화 작업에 유용합니다.
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: null };
  }

  static getDerivedStateFromProps(props, state) {
    // state를 props로부터 파생합니다.
    return null;
  }

  componentDidMount() {
    // 데이터 가져오기 또는 초기화 작업 수행
    fetch('/api/data')
      .then(response => response.json())
      .then(data => this.setState({ data }));
  }

  render() {
    return (
      <div>
        {this.state.data ? this.state.data : 'Loading...'}
      </div>
    );
  }
}

업데이트: props나 state가 변경될 때

컴포넌트의 props나 state가 변경되어 다시 렌더링될 때 순서대로 호출되는 생명 주기 함수들입니다.

  1. getDerivedStateFromProps(props, state)
    1
    
    컴포넌트가 업데이트될 때도 호출됩니다.
    
  2. shouldComponentUpdate(nextProps, nextState)
    1
    2
    
    새로운 props나 state를 받아 컴포넌트를 업데이트할지 여부를 결정합니다.
    성능 최적화에 유용합니다.
    
  3. render()
    1
    
    새로운 state나 props를 반영하여 UI를 다시 그립니다.
    
  4. getSnapshotBeforeUpdate(prevProps, prevState)
    1
    2
    
    DOM이 업데이트되기 직전에 호출됩니다.
    업데이트 전의 DOM 상태를 가져올 수 있습니다.
    
  5. componentDidUpdate(prevProps, prevState, snapshot)
    1
    2
    
    컴포넌트의 업데이트가 완료된 직후에 호출됩니다.
    DOM 조작 등의 후처리 작업에 유용합니다.
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class MyComponent extends React.Component {
  static getDerivedStateFromProps(props, state) {
    return null;
  }

  shouldComponentUpdate(nextProps, nextState) {
    // 조건에 따라 컴포넌트 업데이트를 막을 수 있습니다.
    return true;
  }

  getSnapshotBeforeUpdate(prevProps, prevState) {
    // DOM 업데이트 전의 상태를 캡처합니다.
    return null;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // 업데이트 후 작업 수행
    console.log('Component updated');
  }

  render() {
    return (
      <div>
        {this.props.data}
      </div>
    );
  }
}

소멸: 컴포넌트가 DOM에서 제거될 때

컴포넌트가 DOM에서 제거될 때 호출되는 생명 주기 함수입니다.

  1. componentWillUnmount()
    1
    2
    
    컴포넌트가 DOM에서 제거되기 직전에 호출됩니다.
    정리 작업(예: 타이머 해제, 이벤트 리스너 제거)에 유용합니다.
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MyComponent extends React.Component {
  componentWillUnmount() {
    // 정리 작업 수행
    clearInterval(this.timer);
  }

  render() {
    return (
      <div>
        {this.props.data}
      </div>
    );
  }
}
This post is licensed under CC BY 4.0 by the author.