React 컴포넌트의 생명 주기 개념

박하늘·2025년 2월 14일
0

React

목록 보기
1/15
post-thumbnail

🌱 React 컴포넌트의 생명주기 ( Life Cycle )

컴포넌트가 생성되고 사용되고 소멸될 때 까지 일련의 과정을 말한다.
컴포넌트는 생성(mount)업데이트(update)제거(unmount)의 생명주기를 같는다.


class 컴포넌트 생명주기

📍 중요 메서드

constructor() 컴포넌트가 처음 생성될 때 / 초기 state 설정, 한 번만 실행
render() 컴포넌트가 렌더링될 때마다 실행 / 화면에 UI 업데이트
componentDidMount() 첫 렌더링이 끝난 후 실행 / API 요청, 타이머 설정 등
componentDidUpdate() state나 props가 변경될 때 실행 / 상태 업데이트 시 실행
componentWillUnmount() 컴포넌트가 사라질 때 실행 / 타이머 정리, 이벤트 리스너 제거

📍 예시 코드 ...
showCounter 로 Counter 컴포넌트를 표시/숨기기 가능하며, Counter가 업데이트 되는 코드

import { Component, useState } from "react";
import "./App.css";

function App() {
  const [showCounter, setShowCounter] = useState(false);

  return (
    <>
      {showCounter && <Counter />}
      <br />
      <button onClick={() => setShowCounter((prev) => !prev)}>show?</button>
    </>
  );
}

class Counter extends Component {
  constructor() {
    super();
    this.state = { counter: 1 };
    console.log("constructor");
  }

  componentDidMount() {
    console.log("DidMount");
  }

  componentDidUpdate() {
    console.log("DidUpdate");
  }

  componentWillUnmount() {
    console.log("WillUnmount");
  }

  render() {
    console.log("render");
    return (
      <>
        <div>counter : {this.state.counter}</div>
        <button
          onClick={() => this.setState({ counter: this.state.counter + 1 })}
        >
          +1
        </button>
      </>
    );
  }
}

export default App;

🔮 componentDidMount()

  • 컴포넌트가 화면에 처음 마운트(추가)될 때 실행
  • 한 번만 실행됨 (재렌더링 시 실행되지 않음)

🔮 componentDidUpdate()

  • 컴포넌트가 업데이트될 때 실행됨 (즉, state 또는 props가 변경될 때마다 실행)

🔮 componentWillUnmount()

  • 컴포넌트가 언마운트(제거)될 때 실행됨

함수 컴포넌트 생명주기

📍 React에서는 클래스 컴포넌트 대신 함수형 컴포넌트 + useEffect를 사용하는 것이 일반적
useEffect를 활용하여 생명주기를 구현

import { Component, useEffect, useState } from "react";
import "./App.css";

function App() {
  const [showCounter, setShowCounter] = useState(false);

  return (
    <>
      {showCounter && <Counter />}
      <br />
      <button onClick={() => setShowCounter((prev) => !prev)}>show?</button>
    </>
  );
}

function Counter() {
  const [counter, setCounter] = useState(1);
  const [counter2, setCounter2] = useState(100);

  // 1. 컴포넌트가 최초로 렌더링 될 때에만 조작을 하고싶다!
  useEffect(() => {
    console.log("맨 처음 렌더링 될 때");
  }, []);

  // 2. 컴포넌트가 리렌더링 될 때 조작하고 싶다!
  useEffect(() => {
    console.log("리렌더링...");
  });

  // 3. 특정 상태값이 변할 때에만 조작하고 싶다!
  useEffect(() => {
    console.log("counter의 값이 변할 때");
  }, [counter]);

  useEffect(() => {
    console.log("counter2의 값이 변할 때");
  }, [counter2]);

  // 4. 컴포넌트가 최종적으로 언마운트 될 때 조작하고 싶다! / 처음에도 렌더링 X
  useEffect(() => {
    return () => {
      console.log("컴포넌트 언마운트");
    };
  }, []);

  // 5. 리턴과 특정상태값 변화
  useEffect(() => {
    console.log("counter2의 값이 변할 때");
    return () => {
      console.log("리렌더링 및 사라질 때")
    }
  }, [counter2]);

  // 이렇게 해주면 처음 생성될 때 : counter2의 값이 변할 때

  // counter2의 값이 변할 때 -> 함수 값이 변하면 이전 함수는 지워지고 새로운 컴포넌트가 생긴다
  //  : counter2의 값이 변할 때 , 리렌더링 및 사라질 때





  return (
    <>
      <div>counter : {counter}</div>
      <button onClick={() => setCounter(counter + 1)}>+1</button>
      <div>counter2 : {counter2}</div>
      <button onClick={() => setCounter2(counter2 - 1)}>-1</button>
    </>
  );
}

export default App;

📍 useEffect ...

1️⃣ 기본 구조

useEffect( () => {
    첫번째 인자 : 함수
    return () => { 리턴되는 함수 }
}, [두번째 인자 : 배열 ])


2️⃣ 기본 인자

• 함수 - useEffect가 호출되면 실행될 코드
• 배열 - useEffect가 호출되는 조건을 정의해줄 배열
• 리턴 함수 - useEffect가 사라질 때 실행

3️⃣ 인자 조건별 실행 내용

• 두번째 인자: 배열 = X
   조건 없이 처음 렌더링 되었을 때, 리렌더링 되었을 때 실행

• 두번째 인자: 배열 = []
    처음 렌더링 되었을 때만
  
• 두번째 인자: 배열 = [상태1, 상태2]
    처음 렌더링 되었을 때, 배열에 담긴 값이 변경되어서 리렌더링 되었을 때

• useEffect( ( ) => {
    첫번째 인자 : 함수
    return ( ) => { 리턴되는 함수 }
    })

    함수를 리턴하면?
    컴포넌트가 화면에서 사라질 때(unmount) 실행 된다

class VS 함수형 생명주기

      ㅌ 생명주기 (Life Cycle)             클래스 컴포넌트 (this.state)      함수형 컴포넌트 (useState, useEffect)
마운트 (Mount)componentDidMount()useEffect(() => {...}, [])
업데이트 (Update)componentDidUpdate()useEffect(() => {...}, [state])
언마운트 (Unmount)componentWillUnmount()useEffect(() => { return () => {...}; }, [])

피드백

React 생명주기 함수의 필요성 추가 업로드

0개의 댓글