Post

React 생명 주기 메서드 종류

안녕하세요! 오늘은 React 컴포넌트의 생명 주기 메서드(LifeCycle Methods)의 종류에 대해 알아보겠습니다. 생명 주기 메서드는 컴포넌트의 생성부터 소멸까지의 과정에서 특정 시점에 호출되는 메서드들을 의미합니다. 각 단계에서 호출되는 메서드들을 알아보고, 각각의 역할을 살펴보겠습니다.

React 생명 주기 메서드 종류

1. 마운트(Mounting)

constructor

컴포넌트가 생성될 때 가장 먼저 호출됩니다. 초기 state를 설정하거나 클래스 메서드를 바인딩하는 데 사용됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: 0
        };
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        this.setState({ value: this.state.value + 1 });
    }

    render() {
        return <button onClick={this.handleClick}>{this.state.value}</button>;
    }
}

getDerivedStateFromProps

props로부터 state를 업데이트해야 할 때 사용됩니다. 컴포넌트가 마운트되거나 업데이트될 때 호출됩니다.

1
2
3
4
5
6
7
8
static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.value !== prevState.value) {
        return {
            value: nextProps.value
        };
    }
    return null;
}

render

React 요소를 반환하여 화면에 렌더링합니다. 이 메서드는 필수적으로 구현해야 합니다.

1
2
3
4
5
class MyComponent extends React.Component {
    render() {
        return <div>Hello, World!</div>;
    }
}

componentDidMount

컴포넌트가 처음으로 DOM에 마운트된 직후에 호출됩니다. 여기서 데이터를 가져오거나, DOM을 조작하는 작업을 할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
class MyComponent extends React.Component {
    componentDidMount() {
        console.log('Component has been mounted');
        // 데이터 가져오기 등
    }

    render() {
        return <div>Hello, World!</div>;
    }
}

2. 업데이트(Updating)

shouldComponentUpdate

컴포넌트가 업데이트될지 여부를 결정합니다. 이 메서드는 성능 최적화에 유용합니다.

1
2
3
4
5
6
7
8
9
10
class MyComponent extends React.Component {
    shouldComponentUpdate(nextProps, nextState) {
        // 업데이트 여부를 반환 (true 또는 false)
        return nextProps.value !== this.props.value;
    }

    render() {
        return <div>{this.props.value}</div>;
    }
}

getSnapshotBeforeUpdate

컴포넌트가 DOM에 업데이트되기 직전에 호출됩니다. 이 메서드는 업데이트 이전의 상태를 캡처하여 업데이트 후에 사용할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class MyComponent extends React.Component {
    getSnapshotBeforeUpdate(prevProps, prevState) {
        if (prevProps.value !== this.props.value) {
            return { prevValue: prevProps.value };
        }
        return null;
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        if (snapshot) {
            console.log('Previous value:', snapshot.prevValue);
        }
    }

    render() {
        return <div>{this.props.value}</div>;
    }
}

componentDidUpdate

컴포넌트가 업데이트된 직후에 호출됩니다. 이전 props와 state에 접근할 수 있어, 필요한 후속 작업을 수행할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
class MyComponent extends React.Component {
    componentDidUpdate(prevProps, prevState) {
        if (prevProps.value !== this.props.value) {
            console.log('Component did update');
            // 후속 작업 수행
        }
    }

    render() {
        return <div>{this.props.value}</div>;
    }
}

3. 언마운트(Unmounting)

componentWillUnmount

컴포넌트가 DOM에서 제거되기 직전에 호출됩니다. 여기서 타이머를 정리하거나, 구독을 해제하는 등 클린업 작업을 할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
class MyComponent extends React.Component {
    componentWillUnmount() {
        console.log('Component will unmount');
        // 클린업 작업 수행
    }

    render() {
        return <div>Hello, World!</div>;
    }
}

4. 에러 처리(Error Handling)

componentDidCatch

컴포넌트 렌더링 중에 발생한 오류를 처리할 수 있습니다. 오류 경계를 사용하면, 오류가 발생한 부분만 예외 처리하고 나머지 애플리케이션은 정상적으로 동작하게 할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
class MyComponent extends React.Component {
    componentDidCatch(error, info) {
        console.log('Error caught:', error, info);
        // 오류 로깅 등
    }

    render() {
        if (this.state.hasError) {
            return <h1>Something went wrong.</h1>;
        }
        return <div>Hello, World!</div>;
    }
}

5. 함수형 컴포넌트와 훅(Hooks)

함수형 컴포넌트에서는 생명 주기 메서드를 직접 사용할 수 없지만, React Hooks를 통해 동일한 기능을 구현할 수 있습니다. 다음은 useEffect 훅을 사용한 예제입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React, { useState, useEffect } from 'react';

function MyComponent() {
    const [value, setValue] = useState(0);

    useEffect(() => {
        console.log('Component did mount');
        
        return () => {
            console.log('Component will unmount');
        };
    }, []);

    useEffect(() => {
        console.log('Component did update', value);
    }, [value]);

    return (
        <div>
            <p>{value}</p>
            <button onClick={() => setValue(value + 1)}>Increment</button>
        </div>
    );
}

이 예제에서는 useEffect 훅을 사용하여 componentDidMount, componentDidUpdate, componentWillUnmount의 기능을 구현했습니다.

결론

React 생명 주기 메서드는 컴포넌트의 특정 시점에 실행되는 메서드들로, 컴포넌트의 상태 변화에 따라 적절한 처리를 할 수 있도록 도와줍니다. 클래스형 컴포넌트에서는 생명 주기 메서드를 직접 사용할 수 있고, 함수형 컴포넌트에서는 훅을 통해 동일한 기능을 구현할 수 있습니다.

오늘도 제 글을 읽어주셔서 감사합니다. 다음 시간에 더 유익한 주제로 찾아뵙겠습니다.

This post is licensed under CC BY 4.0 by the author.