Gapus Dev Blog

[React] 리액트의 생명 주기(Life Cycle) 본문

프론트엔드/React

[React] 리액트의 생명 주기(Life Cycle)

Gapus 2023. 11. 27. 08:00

React의 생명 주기

 

리액트의 생명 주기

 

생명 주기의 3가지 단계

 

1. 마운트(Mount) - 생성 단계

컴포넌트가 생성되어 DOM에 삽입될 때 발생

 

  • constructor - 컴포넌트가 생성될 때 호출되는 함수
  • static getDerivedStateFromProps - props에 변화가 있을 때마다 호출되며, state를 업데이트하는 데 사용
  • render - 컴포넌트의 UI를 렌더링
  • componentDidMount - 컴포넌트가 마운트된 직후에 호출, 외부 데이터 가져오기, 이벤트 등록 등의 작업을 수행

 

2. 업데이트(Update) - 업데이트 단계

컴포넌트의 props나 state가 변경되어 업데이트가 발생할 때 호출

 

  • static getDerivedStateFromProps - 마운트 단계와 마찬가지로 props에 변화가 있을 때마다 호출되며,
    state를 업데이트하는 데 사용
  • shouldComponentUpdate - 컴포넌트의 업데이트 여부를 결정하는 메서드, 성능 최적화에 사용 가능
  • render - 컴포넌트의 UI를 업데이트
  • componentDidUpdate - 컴포넌트의 업데이트가 완료된 후 호출, DOM 업데이트 후 추가 작업을 수행 가능

 

3. 언마운트(Unmount) - 제거 단계

컴포넌트가 제거되어 DOM에서 제거될 때 호출

 

  • componentWillUnmount - 컴포넌트가 제거되기 직전에 호출, 이벤트 등록 해제, 타이머 제거 등의 작업을 수행

 


 

클래스형 컴포넌트 예시

 

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  static getDerivedStateFromProps(props, state) {
    // props나 state가 변경될 때마다 호출되며, 새로운 state를 반환하여 업데이트할 수 있습니다.
    return null;
  }

  componentDidMount() {
    // 컴포넌트가 마운트된 직후에 호출됩니다.
    // 외부 데이터 가져오기, 이벤트 등록 등의 작업을 수행할 수 있습니다.
  }

  shouldComponentUpdate(nextProps, nextState) {
    // 컴포넌트의 업데이트 여부를 결정하는 메서드입니다.
    // 성능 최적화를 위해 사용될 수 있습니다.
    return true;
  }

  componentDidUpdate(prevProps, prevState) {
    // 컴포넌트의 업데이트가 완료된 후 호출됩니다.
    // DOM 업데이트 후 추가 작업을 수행할 수 있습니다.
  }

  componentWillUnmount() {
    // 컴포넌트가 제거되기 직전에 호출됩니다.
    // 이벤트 등록 해제, 타이머 제거 등의 작업을 수행할 수 있습니다.
  }

  handleClick = () => {
    this.setState(prevState => ({
      count: prevState.count + 1
    }));
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.handleClick}>Increase Count</button>
      </div>
    );
  }
}

 


 

함수형 컴포넌트 예시

 

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log('마운트됨');

    return () => {
      console.log('언마운트됨');
    };
  }, []);

  useEffect(() => {
    console.log('count 업데이트됨');
  }, [count]);

  const handleClick = () => {
    setCount(prevCount => prevCount + 1);
  };

  console.log('렌더링됨');

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increase Count</button>
    </div>
  );
}

 

 


 

오류 처리 메서드 예시

 

componentDidCatch

  • 컴포넌트 내에서 발생한 에러를 처리하기 위한 생명 주기 메서드
  • 이 메서드를 사용하여 에러를 잡고, 에러 상황에 대한 대체 UI를 렌더링하거나 로깅 가능
  • 렌더링 단계에서 실행

 

import React, { Component } from 'react';

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hasError: false
    };
  }

  componentDidCatch(error, errorInfo) {
    console.error('에러가 발생했습니다:', error);
    console.error('에러 정보:', errorInfo);
    this.setState({ hasError: true });
  }

  render() {
    if (this.state.hasError) {
      return <p>에러가 발생했습니다. 죄송합니다.</p>;
    }
    return this.props.children;
  }
}

export default ErrorBoundary;