상세 컨텐츠

본문 제목

React 라이프 사이클

개발

by 동동주1123 2023. 11. 9. 14:32

본문

마운팅(Mounting)


constructor:
컴포넌트가 생성될 때 호출됩니다. 초기 상태 초기화 및 메소드 바인딩을 수행하는 데 사용됩니다.

render:
컴포넌트가 렌더링될 때 호출됩니다. UI를 렌더링하는 역할을 합니다.

componentDidMount:
컴포넌트가 마운트(렌더링이 완료되고 DOM에 추가됨)된 직후에 호출됩니다. API 호출, 구독 설정, 초기화 등의 작업을 수행하는 데 사용됩니다.


업데이트(Updating)

getDerivedStateFromProps:
새로운 props가 전달될 때, 상태를 업데이트하는데 사용됩니다.

shouldComponentUpdate:
컴포넌트가 업데이트 되어야 하는지 여부를 결정하는 메소드로, 성능 최적화에 사용됩니다.

render:
컴포넌트가 다시 렌더링될 때 호출됩니다.


getSnapshotBeforeUpdate:
실제 DOM에 변화가 일어나기 직전에 호출되며, 이전의 값을 가져오거나 스크롤 위치와 같은 정보를 얻는데 사용됩니다.

componentDidUpdate:
컴포넌트가 업데이트를 완료한 직후에 호출됩니다. 업데이트 후의 작업을 처리하는 데 사용됩니다.

언마운팅(Unmounting)


componentWillUnmount:
컴포넌트가 언마운트(제거)되기 직전에 호출됩니다. 구독 해제, 리소스 정리 등의 작업을 수행하는 데 사용됩니다.


에러 처리(Error Handling)


componentDidCatch:
하위 컴포넌트의 에러를 잡는데 사용되며, 컴포넌트 트리 내에서 에러를 처리하는 메소드입니다.

 


이 라이프사이클 메소드들을 사용하여 컴포넌트가 생성되고, 업데이트되며, 파괴될 때 원하는 동작을 수행할 수 있습니다. 최신 버전의 React에서는 몇몇 라이프사이클 메소드가 deprecated되고 새로운 라이프사이클 API가 추가되었으므로, 최신 문서를 참조하여 사용하시는 것이 좋습니다.

 

import React, { Component } from 'react';

class LifecycleExample extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      hasError: false
    };
    console.log('constructor');
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    console.log('getDerivedStateFromProps');
    return null;
  }

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

  shouldComponentUpdate(nextProps, nextState) {
    console.log('shouldComponentUpdate');
    return true;
  }

  getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log('getSnapshotBeforeUpdate');
    return null;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log('componentDidUpdate');
  }

  componentWillUnmount() {
    console.log('componentWillUnmount');
  }

  static getDerivedStateFromError(error) {
    console.log('getDerivedStateFromError');
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    console.log('componentDidCatch');
  }

  increaseCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    console.log('render');
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return (
      <div>
        <h2>Lifecycle Methods Example</h2>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increaseCount}>Increase Count</button>
      </div>
    );
  }
}

export default LifecycleExample;

'개발' 카테고리의 다른 글

Mysql 힌트 종류  (0) 2023.04.15
JAVASCRIPT 프로미스 , 제네레이터  (0) 2023.04.09
JAVA XML 파싱방법 XmlPull 이용  (0) 2023.04.09

관련글 더보기