[React] State와 Lifecycle

J.·2024년 5월 15일

React

목록 보기
3/11
post-thumbnail

🔍 한눈에 알아보기

State

  • Component의 변경 가능한 데이터
  • 사전 정의가 되지 않으며, 개발자가 직접 정의
  • 렌더링이나 데이터 흐름에 사용되는 값만 포함
  • 직접 수정이 가능하지만 하면 안됨 (함수를 사용해 변경)

Lifecycle (생명 주기)

  • Component의 생명 주기
  • 세 가지 단계로 나뉨
    • Mounting
      • Constructor (생성자)가 실행되며 rendering 됨
      • 생명주기 함수 componentDidMount 실행
    • Updating
      • 지속적으로 update가 되며 re-rendering 됨
      • 생명주기 함수 componentDidUpdate 실행
    • Unmounting
      • 상위 component에서 하위 component를 더 이상 표시하지 않을 때
      • 생명주기 함수 componentWillUnmount 실행

효과

  • 꼭 필요할 때만 update와 rendering을 실행해 component들이 정확하고 효율적이게 작동하게 함

📌State

State를 직역하면 상태라는 뜻을 의미한다.

React에서의 state는 component의 상태 보다는 그의 변경 가능한 데이터를 표현한다.

다음 코드를 살펴보자.

import React, { useState } from 'react';

function Counter() {
    // 'count'라는 state 변수와 'setCount'라는 state 함수를 정의
    // 'count'의 초기 값을 0으로 설정
    const [count, setCount] = useState(0);

    return (
        <div>
            <h1>Counter: {count}</h1> {/* 현재 count를 출력 */}
            <button onClick={() => setCount(count + 1)}>더하기</button> {/* count를 더함 */}
            <button onClick={() => setCount(count - 1)}>빼기</button> {/* count를 뺌 */}
            <button onClick={() => setCount(0)}>초기화</button> {/* count를 0으로 초기화 시킴 */}
        </div>
    );
}

export default Counter;

1) hook의 사용

먼저 useState라는 hook을 사용해 function component에 count state 변수와 setCount라는 state 함수를 추가해줬다. (hook은 이후 글에서 자세히 설명할 예정이다)

2) State initialization (초기화)

useState(0)이라는 함수 사용을 살펴보면 state 변수인 count의 초기값을 0으로 지정해준 것이다.

3) State 변수/함수 사용

Counter component의 return 값에서 <h1>태그 안에 count라는 state 변수를 쉽게 출력해준 것 처럼 쉽게 사용할 수 있다.

그 밑에 button들에서 setCount 함수가 어떻게 사용되는지 확인해보자.

state는 직접 수정/변경이 되면 안되며, 함수를 사용해 값을 변경해야한다.

이때 사용되는 함수가 set 함수이다.

setCount 함수가 호출될 때 Counter component는 다시 렌더링을 거쳐 UI에 표시 될 값을 업데이트한다.


📌Lifecycle

Component도 인간과 같이 생명주기가 있다.

출생, 인생, 사망 세 단계를 거친다고 생각하면 쉽다.

이를 설명하기 위해 앞서 사용한 function component와 같은 기능을 하는 class component의 코드를 살펴보자.

Function componentclass component가 뭔지 모른다면 아래 글을 참고하자.

[React] Function component와 class component

import React from 'react';

class Counter extends React.Component {
    constructor(props) {
        super(props);
        // State initialization
        this.state = { count: 0 };
    }

    // Lifecycle method: componentDidMount
    componentDidMount() {
        console.log('Counter component mounted');
    }

    // Lifecycle method: componentDidUpdate
    componentDidUpdate() {
        console.log(`Component updated. New count: ${this.state.count}`);
    }

    // Lifecycle method: componentWillUnmount
    componentWillUnmount() {
        console.log('Component will unmount...');
    }

    // count 더하기
    increase = () => {
        this.setState({ count: this.state.count + 1 });
    }

    // count 빼기
    decrease = () => {
        this.setState({ count: this.state.count - 1 });
    }

    // count 초기화
    reset = () => {
        this.setState({ count: 0 });
    }

    render() {
        return (
            <div>
                <h1>Counter: {this.state.count}</h1>
                <button onClick={this.increase}>더하기</button>
                <button onClick={this.decrease}>빼기</button>
                <button onClick={this.reset}>초기화</button>
            </div>
        );
    }
}

export default Counter;

생명주기 함수

여기에서는 앞에 코드 예제에서는 볼 수 없었던 생명주기 함수들이 있다:

  • Mounting: componentDidMount()
    • Component가 처음으로 렌더링 되어 DOM에 추가가 될 때 한 번 실행이 된다.
  • Updating: componentDidUpdate()
    • Component가 업데이트 될 때마다 계속 실행되는 함수이다.
  • Unmounting: componentWillUnmount()
    • Component가 DOM에서 사라지기 전에 한 번 실행되는 함수이다.
    • 보통 timer를 invalidate 시키거나 첫 번째 함수인 componentDidMount에서 설정된 event listner를 삭제하는 역할을 한다.
profile
코린이 (코인 어린이 아니라 코딩 어린이임)

0개의 댓글