본문 바로가기
Front-End/JAVASCRIPT

[React.js] 리액트 생명주기에 대해서

by You_mool 2024. 2. 19.
반응형

리액트의 컴포넌트 생명주기(Lifecycle)는 크게 3가지 단계로 나눌 수 있습니다.

마운팅(Mounting): 컴포넌트 인스턴스가 생성되어 DOM에 삽입될 때 발생하는 단계입니다.
업데이트(Updating): props 또는 state의 변화에 따라 컴포넌트 인스턴스가 재렌더링되는 단계입니다.
언마운팅(Unmounting): 컴포넌트 인스턴스가 DOM에서 제거되는 단계입니다.

1. 마운팅

- constructor(): 컴포넌트가 생성될 때 호출되며, state 초기화 등을 할 수 있습니다.
- static getDerivedStateFromProps(): props로 받아온 값을 state에 동기화시키는 용도로 사용합니다.
- render(): 컴포넌트를 렌더링합니다.
- componentDidMount(): 컴포넌트가 마운트된 직후, 즉 DOM에 삽입된 직후 호출됩니다. Ajax 요청, DOM 조작 등의 작업을 수행합니다.


2. 업데이트

- static getDerivedStateFromProps(): 이 메서드는 마운팅 단계뿐만 아니라 업데이트 단계에서도 호출됩니다.
- shouldComponentUpdate(): 컴포넌트가 리렌더링을 할지 결정합니다. 이 메서드가 false 값을 반환하면 이후 render()와 componentDidUpdate()는 호출되지 않습니다.
- render(): 컴포넌트를 렌더링합니다.
- getSnapshotBeforeUpdate(): 컴포넌트가 업데이트 되기 직전, 렌더링 결과가 DOM에 반영되기 직전에 호출됩니다.
- componentDidUpdate(): 컴포넌트의 업데이트 작업이 끝난 후 호출됩니다.
3. 언마운팅

- componentWillUnmount(): 컴포넌트가 DOM에서 제거되기 직전에 호출됩니다. 이벤트 제거 등의 정리 작업을 수행합니다.

class ExampleComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { color: 'green' };
  }

  static getDerivedStateFromProps(props, state) {
    return { color: props.color ? props.color : state.color };
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== nextProps.color) {
      return true;
    }
    return false;
  }

  render() {
    return (
      <div style={{ color: this.state.color }}>
        {this.props.message}
      </div>
    );
  }

  componentDidMount() {
    console.log('Component mounted');
  }

  componentDidUpdate() {
    console.log('Component updated');
  }

  componentWillUnmount() {
    console.log('Component will unmount');
  }
}

이 컴포넌트는 props로 message와 color를 받습니다. color가 변경되면 새로운 color로 렌더링하며, 그렇지 않으면 기존 state의 color를 사용해 렌더링합니다. 또한 각 생명주기에서 콘솔에 로그를 출력합니다.

반응형