Lifecycle methods in React Component and explain each method.

cptkuk91·2023년 1월 31일
1

Tech Interview

목록 보기
7/7

lifecycle methods in React.

React Component의 생명주기 Method는 특정 순간에 자동으로 호출되는 Method입니다.

  1. componentDidMount: Component가 처음 Rendering 될 때 DOM에 추가된 후 호출됩니다.

  2. shouldComponentUpdate: Rendering 전 호출되어 Rerendering 필요한지 판단 후 호출됩니다.

  3. componentDidUpdate: Component가 갱신되어 Rerendering 후 호출됩니다.

  4. componentWillUnmount: Component가 DOM에서 제거되기 전 호출됩니다.

  5. getDerivedStateFromProps: Rendering 전 호출되어 Component의 상태를 props를 기반으로 업데이트할 수 있습니다.

  6. getSnapshotBeforeUpdate: Rendering 전 호출되어 Component가 DOM에서 정보를 캡처할 수 있도록 합니다.

Lifecycle methods of a React Component are methods that are automatically called at specific moments during the lifetime of a component. The following are the main lifecycle methods in React.

  1. componentDidMount: Called after the component has been rendered for the first time and added to the DOM

  2. shouldComponentUpdate: Called before rendering the component to determine if a Re-render is necessary.

  3. componentDidUpdate: Called after the component has been updated and re-rendered.

  4. componentWillUnmount: Called just before the component is removed from the DOM.

  5. getDerivedStateFromProps: Called before rendering the component and allows for the component's state to be updated based on the next set of props.

  6. getSnapShotBeforeUpdate: Called just before rendering and allows the component to capture some information from the DOM.

import React, { Component } from 'react';

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

  static getDerivedStateFromProps(props, state) {
    // This method is called before render method and used to update state based on changes in props.
    return null;
  }

  componentDidMount() {
    // This method is called after the component is mounted to the DOM.
    // You can make API calls or do any other setup logic here.
  }

  shouldComponentUpdate(nextProps, nextState) {
    // This method is called before render method and used to determine if render method should be called or not.
    // It returns true if render method should be called, otherwise false.
    return true;
  }

  getSnapshotBeforeUpdate(prevProps, prevState) {
    // This method is called before render method and used to capture the state of the component before the render method is called.
    return null;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // This method is called after render method and used to perform any post-render logic.
  }

  componentWillUnmount() {
    // This method is called just before the component is unmounted from the DOM.
    // You can perform any cleanup logic here.
  }

  render() {
    return <div>Hello World!</div>;
  }
}

export default MyComponent;
profile
메일은 매일 확인하고 있습니다. 궁금하신 부분이나 틀린 부분에 대한 지적사항이 있으시다면 언제든 편하게 연락 부탁드려요 :)

0개의 댓글