본문으로 바로가기
반응형

https://ko.wikipedia.org

<"리액트를 다루는 기술" 책 참조>


LifeCycle (수명주기) 예제를 진행하던 중 constructor에 consloe.log가 두 번 실행되어 있었습니다.

 

LifeCycle 수명 주기 예제 소스

import React, { Component } from 'react';

class LifeCycleSample extends Component {
    state = {
        number: 0,
        color: null
    };

    myRef = null; //ref 설정할 부분

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

    /*
    props로 받아 온 값을 state에 동기화시키는 용도
    컴포넌트가 마운트, 업데이트될 떄 호출
    */
    static getDerivedStateFromProps(nextProps, prevState) {
        console.log('getDerivedStateFromProps - ' + nextProps.color + '-' + prevState.color + '-');
        if (nextProps.color !== prevState.color) {
            return { color: nextProps.color };
        }
        return null;
    }

    /*
    첫 렌더링 이후 호출
    - 자바스크립트 라이브러리 또는 프레임워크 함수 호출
    - 이벤트 등록
    - setTimeout, setInterval, 네트워크 요청 같은 비동기 작업 처리
    */
    componentDidMount() {
        console.log('componentDidMount');
    }

    /*
    props, state 변경시 리렌더링을 시작할지 여부 체크, default값 true
    */
    shouldComponentUpdate(nextProps, nextState) {
        console.log('shouldComponentUpdate', nextProps, nextState);
        //숫자의 마지막 자리가 4면 리렌더링하지 않습니다.
        return nextState.number % 10 !== 4;
    }

    /*
    componentDidMount에서 등록한 이벤트, 타이머, 직접생성한 DOM 제거 작업
    */
    componentWillUnmount() {
        console.log('componentWillUnmount');
    }

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

    /*
    render에서 만들어진 결과물이 브라우저에 실제로 반영되기 직전에 호출.
    */
    getSnapshotBeforeUpdate(prevProps, prevState) {
        console.log('getSnapshopBeforeUpdate');
        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;

index.js 파일

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

두 번 실행 되는 이유는 <React.StrictMode></React.StrictMode>

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic.
This is done by intentionally double-invoking the following functions:

Class component constructor, render, and shouldComponentUpdate methods
Class component static getDerivedStateFromProps method
Function component bodies
State updater functions (the first argument to setState)
Functions passed to useState, useMemo, or useReducer
Note: This only applies to development mode. Lifecycles will not be double-invoked in production mode.


Strict mode는 자동으로 부작용을 감지 할 수는 없지만 조금 더 결정적으로 만들어 부작용을 발견하는 데 도움이 될 수 있습니다.
이 작업은 의도적으로 다음 함수를 두 번 호출하여 수행됩니다.
- 클래스 구성 요소 생성자, 렌더링 및 shouldComponentUpdate 메서드
- 클래스 구성 요소 정적 getDerivedStateFromProps 메서드
- 기능 구성 요소 본문
- 상태 업데이터 함수(setState에 대한 첫 번째 인수)
- useState, useMemo 또는 useReducer에 전달된 함수
참고: 이는 개발 모드에만 적용됩니다. 수명 주기는 프로덕션 모드에서 이중 호출되지 않습니다.
반응형