본문 바로가기
프론트엔드/React

리액트 React | 노마스 코더 영화 평점 웹서비스 | 컴포넌트 생명주기 함수: 마운트, 업데이트, 언마운트, 에러 처리

by YUNI Heo 2023. 4. 3.
반응형

 

✅ 생명주기 함수

컴포넌트가 생성, 업데이트, 소멸될 때 호출되는 일련의 메서드이다.

생명 주기 함수를 통해 컴포넌트의 동작을 제어하고, 상태를 갱신하거나 데이터를 가져온다.

 

함수 실행 순서

  1. constructor() 함수: 컴포넌트가 생성될 때 호출되며, 초기화 작업을 수행한다.
  2. static getDerivedStateFromProps() 함수: 컴포넌트가 생성될 때와 업데이트될 때 호출되며, 프로퍼티 값을 상태 값으로 변환을 수행한다.
  3. render() 함수: 컴포넌트의 UI를 생성하고 반환을 수행한다.
  4. componentDidMount() 함수: 컴포넌트가 마운트 된 후에 호출되며, 초기화 및 네트워크 요청 등의 작업을 수행한다.
  5. shouldComponentUpdate() 함수: 컴포넌트가 업데이트될 때 호출되며, 다음 렌더링이 필요한지 여부를 결정한다.
  6. static getDerivedStateFromProps() 함수: 컴포넌트가 업데이트될 때 호출되며, 프로퍼티 값을 상태 값으로 변환을 수행한다.
  7. render() 함수: 컴포넌트의 UI를 다시 생성하고 반환을 수행한다.
  8. getSnapshotBeforeUpdate() 함수: 컴포넌트가 업데이트된 후에 호출되며, DOM 변경 전에 추가 작업을 수행한다.
  9. componentDidUpdate() 함수: 컴포넌트가 업데이트된 후에 호출되며, 이전 상태와 비교해서 추가 작업을 수행한다.
  10. componentWillUnmount() 함수: 컴포넌트가 제거되기 전에 호출되며, 타이머나 이벤트 리스너 등을 해제하는 등의 정리 작업을 수행한다.

 

💡 마운트 Mounting

컴포넌트가 DOM에 처음으로 생성될 때 호출되는 함수이다.

  • constructor() 함수
  • static getDerivedStateFromProps() 함수
  • render() 함수
  • componentDidMount() 함수

constructor() 함수

  • 객체를 생성할 때 초기화를 수행한다.
  • 객체가 생성될 때 필요한 모든 props와 메서드를 설정한다.
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  sayHello() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

const john = new Person("John", 30);
john.sayHello(); // 출력 결과: "Hello, my name is John and I am 30 years old."

componentDidMount() 함수

  • 컴포넌트가 DOM에 렌더링 된 직후에 실행되는 코드를 작성한다.
  • 데이터를 불러오거나 다른 비동기 작업을 수행한다.
class MyComponent extends React.Component {
  componentDidMount() {
    console.log('Component mounted!');
  }

  render() {
    return <h1>Hello, world!</h1>;
  }
}

 

💡 업데이트 Updating

컴포넌트가 업데이트되어 다시 렌더링될 때 호출되는 함수이다.

  • static getDerivedStateFromProps() 함수
  • shouldComponentUpdate() 함수
  • render() 함수
  • getSnapshotBeforeUpdate() 함수
  • componentDidUpdate() 함수

componentDidUpdate() 함수

  • 컴포넌트가 업데이트된 후에 실행되는 코드를 작성한다.
  • 이전의 props와 상태 값을 비교해서 변경된 부분에 대한 작업을 수행한다.
class MyComponent extends React.Component {
  componentDidUpdate(prevProps, prevState) {
    if (this.props.value !== prevProps.value) {
      console.log('Value changed!');
    }
  }

  render() {
    return <h1>{this.props.value}</h1>;
  }
}

 

💡 언마운트 Unmounting

컴포넌트가 DOM에서 제거될 때 호출되는 함수이다.

  • componentWillUnmount() 함수

componentWillUnmount() 함수

  • 컴포넌트가 제거되기 전에 필요한 정리 작업을 수행한다.
  • 이벤트 핸들러를 제거하고, 타이머를 해제하고, 네트워크 요청을 취소하는 등의 작업을 수행한다.
class MyComponent extends React.Component {
  componentDidMount() {
    this.timerID = setInterval(() => {
      console.log('Tick');
    }, 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  render() {
    return <h1>Hello, world!</h1>;
  }
}

 

💡 에러 처리

  • static getDerivedStateFromError() 함수
  • componentDidCatch() 함수
반응형