Multi Developer SuHo

리액트 라이프사이클(Life Cycle)이 뭐길래? 쉽게 이해하는 생명주기 본문

React 기록

리액트 라이프사이클(Life Cycle)이 뭐길래? 쉽게 이해하는 생명주기

Dreaming Developer Student 2025. 4. 23. 20:30
SMALL

안녕하세요~ 저번에는 리액트에 대한 개념을 알아보았습니다. 이번에는 리액트에서 중요한 생명주기에 대해 알아보겠습니다. 

📑목차
1. 생명주기
1-1. 리액트 생명주기란?
1-2. 컴포넌트의 생명주기 3단계
1-3. Mounting(마운팅)
1-4. Updating(업데이트)
1-5. Unmounting(언마운팅)
1-6. 클래스형 컴포넌트 생명주기 코드


서론

리액트를 처음 접했을 때 가장 헷갈렸던 부분 중 하나가 바로 생명주기(Life Cycle)였습니다. 컴포넌트가 언제 생성되고, 업데이트되고, 사라지는지 그 흐름을 이해하는 건 상태 관리와 성능 최적화에도 큰 도움이 됩니다. 이번 글에서는 리액트의 생명주기를 클래스형 컴포넌트를 통해 설명해보도록 하겠습니다. 

 

본론

1.  생명주기(Life Cycle)

 

1-1. 리액트 생명주기란?

컴포넌트가 생성되어 화면에 렌더링되고, 상태변화에 따라 업데이트 되며,  소멸되는 과정을 말합니다.

 

 

1-2. 리액트 생명주기 3단계

리액트 생명주기는 총 3단계의 과정을 거칩니다. 각각의 단계에서는 컴포넌트가 어떻게 시작되고, 변화하고, 끝나는지를 보여주는 흐름입니다. 

 

1. 마운트(componentDidMount) : 컴포넌트가 최초로 생성될때 한번만 실행
    1-1. Constructor :  컴포넌트 생성시 최초 한번 호출
    1-2. 등등 상태 초기화
    1-3. render : JSX를 변환해서 자바스크립트로 UI를 출력
    1-4. componentDidMount : 컴포넌트가 DOM을 모두 출력한 이후에 실행되는 메서드 (axios등의 비동기 통신)
2. 업데이트 (componentDidUpdate) :  props와 state가 변경되면 컴포넌트를 다시 리렌더링 하고 호출된다.
    2-1. 상태가 변경되면 상태를 업데이트
    2-2. render : 상태변수가 변경된 내용으로 UI출력
    2-3. componentDidUpdate : 상태변수가 변경되고 나서 변경된 상태변수를 호출해서 사용할때
3. 언마운트 (componentWillUnmount) : 컴포넌트가 화면 즉 렌더링하는 요소에서 사라지면 발생

 

 

1-3. Mounting(생성 단계)

컴포넌트가 처음 화면에 렌더링 되는 단계입니다. 이 단계에서는 초기값을 설정하거나, 외부 데이터를 불러오는 작업을 합니다.

 

 

1-4. Updating(업데이트 단계)

컴포넌트가 State 또는 props의 변경으로 인해 다시 화면을 리렌더링 합니다.

 

 

1-5. Unmounting(제거 단계)

컴포넌트가 부모 컴포넌트에 의해 제거되고 화면에 나타나지 않을때 실행되는 단계입니다.

 

 

 

 

1-6. 클래스형 컴포넌트 생명주기 코드

Card.jsx 코드

import { Component } from "react";

export default class Card extends Component {
  // 여기서 props를 전달받을 수 있다
  constructor(props) { // 생성자를 호출할 때 props를 전달받음
    super(props); // 부모 생성자 호출
    console.log(props); // {} 빈 객체 출력
    // 상태

    this.state = {
        count : 0,
        user : "이수호"
    }
  }


  // 초기에 상태가 업데이트 되서 렌더링
  componentDidMount(){
    console.log(this.state.count);
    console.log(this.state.user);
    console.log("나 이제 탄생했어~~")
  }

  componentDidUpdate(){
    console.log("내가 변화했어 성장기야~")
    this.reward(this.state.count);
}

  increamentCounter = () => {
    this.setState({count : this.state.count + 1});
    console.log("카운트가 증가되었습니다 : ", this.state.count)
  }

  decreamentCounter = () => {
    this.setState({count : this.state.count - 1});
    console.log("카운트가 감소되었습니다 : ", this.state.count)
  }

  reward = (count) => {
    if(count >= 10){
        console.log("보상 당첨!!!!")
    }
  }

  changeName = (newUser) => {
    this.setState({user : newUser}, () => {
      console.log("사용자 이름이 변경되었습니다!", this.state.user)
    })
  }

    render(){
        console.log(`${this.props.content} 나 렌더링 되었어!!!`)
        return (
            <div className="card">
                <div>내 카운트 : {this.state.count}</div>
                <input type="text" value={this.state.user} onChange={(e) => this.changeName(e.target.value)}/>
                <div className="title"></div>
                <div className="contnet"></div>
                <div>{this.props.content}</div>
                <div>1234</div>
                <button onClick={this.increamentCounter}>증가</button>
                <button onClick={this.decreamentCounter}>감소</button>
            </div>
        )
    }
}

 

 

결론

LIST