본문 바로가기

Web/React & Next.js

컴포넌트의 라이프사이클 메서드

마운트 : DOM이 생성되고 웹 브라우저상에 나타나는 것

constructor: 컴포넌트 새로 만들 때 마다 호출되는 클래스 생성자 메서드

                컴포넌트를 만들 때 처음으로 생성된다

getDerivedStateFromProps: props에 있는 값을 state에 넣을 때 사용

render: ui을 랜더링 하는 메서드

componentDidMount: 컴포넌트가 웹 브라우저상에 나타난 후 호출하는 메서드

                             비동기 작업을 처리(이벤트 등록, 네트워크 요청, 다른 자바스크립트 라이브러리 함수 호출..등)

 

업데이트

업데이트 할 경우

1. props가 바뀔 때

2. state가 바뀔 때

3. 부모 컴포넌트가 리렌더 될때

4. this.forceUpdate로 강제로 렌더링을 트리거할 때

 

getDerivedStateFromProps: props의 변화에 따라 state값에도 변화를 주고 싶을 때 사용

shouldComponentUpdate: 컴포넌트가 리렌더링 할지 말지 결정하는 메서드

                                   반드시 true, false를 반환, 만약 false 반환하면 업데이트는 중지

render: 컴포넌트 리렌더링

getSnapshotBeforeUpdate: 컴포넌트 변화를 DOM에 반영하기 바로 직전에 호출

                                   업데이트 직전 값을 참고할 일 있을 때 사용(스크롤바 위치 유지)

componentDidUpdate: 컴포넌트 업데이트 작업이 끝난 후 호출하는 메서드

                              컴포넌트가 이전에 가졌던 데이터에 접근할 수 있고

                              getSnapshotBeforeUpdate 반환 값을 받을 수 있다

 

언마운트: 마운트의 반대, 컴포넌트를 DOM에서 제거함

componentWillUnmount: 컴포넌트가 웹 브라우저 상에서 사라지기 전에 호출하는 메서드

                                  컴포넌트를 DOM에 제거할 때 실행

componentDidCatch: 렌더 중 오류가 발생했을때어플이 먹통되지 않고 오류 ui를 보여준다

 

import { Component } from 'react';

class LifeCycleSample extends Component{

    state ={
        number: 0,
        color: null
    }

    myRef= null;

    constructor(props){
        super(props);
        console.log('constructor');
    }

    static getDerivedStateFromProps(nextProps, prevState){
        console.log('getDerivedStateFromProps');
        if(nextProps.color !== prevState.color){
            return {color : nextProps.color};
        }
        return null;
    }

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

    shouldComponentUpdate(nextProps, nextState){
        console.log('shouldComponentUpdate',nextProps, nextState);
        return nextState.number % 10 !== 4;
    }

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

    handleClick =() =>{
        this.setState({
            number: this.state.number +1
        });
    }

    getSnapshotBeforeUpdate(prevProps, prevState){
        console.log('getSnapshotBeforeUpdate');
        if(prevProps.color !== this.props.color){
            return this.myRef.style.color;
        }
        
        return null;
    }

    componentDidUpdate(prevProps, prevState,snapshot){
        console.log('componentDidUpdate',prevProps, prevState);
        if(snapshot){
            console.log('업데이트되기 직전 색상:',snapshot );
        }
    }

    render(){
        console.log('render');

        const style ={
            color: this.props.color
        };

        return(
            <div>
                <h1 style={style} ref={ref => this.myRef =ref}>
                    {this.state.number}
                </h1>
                <p>color: {this.state.color}</p>
                <button onClick={this.handleClick}>더하기</button>
            </div>
        );
    }
}

export default LifeCycleSample;
import LifeCycleSample from "./LifeCycleSample";

function getRandomColor(){
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
}

class App extends Component{

  state ={
    color: '#000000'
  }

  handleClick = () =>{
    this.setState({
      color: getRandomColor()
    });
  }

  render(){
    return(
      <div>
        <button onClick={this.handleClick}>랜덤 색상</button>
        <LifeCycleSample color={this.state.color}/>
      </div>
    );
  }
}

업데이트 할때 state값이 변화하기 때문에 getDerivedStateFromProps가 실행된다

componentDidUpdate로 이전 데이터 값을 확인하고

shouldComponentUpdate의 return 조건에 따라 update가 되거나 안된다. 10으로 나눴을때 4가 나머지면 false한다

componentDidMount, constructor은 첫 렌더에만 호출된다

render는 업데이트 될 때 마다 호출된다

import { Component } from 'react';

class ErrorBoundary extends Component{

    state ={
        error: false
    };

    componentDidCatch(error,info){
        this.setState({
            error: true
        });
        console.log({error,info});
    }

    render(){
        if(this.state.error) return <div>에러가 발생했습니다.</div>
        return this.props.children; 
    }

}

export default ErrorBoundary;
import ErrorBoundary from "./ErrorBoundary";

 <ErrorBoundary>
          <LifeCycleSample color={this.state.color}/>
  </ErrorBoundary>

에러 발생할시 <div>에러가 발생했습니다</div>을 리턴

'Web > React & Next.js' 카테고리의 다른 글

컴포넌트 스타일링  (0) 2022.04.06
Hooks  (0) 2022.04.06
컴포넌트 반복  (0) 2022.04.04
DOM에 이름 달기  (0) 2022.04.03
이벤트 핸들링  (0) 2022.04.03