React 생명 주기 함수(LifeCycle)
안녕하세요! 오늘은 React에서 컴포넌트의 생명 주기 함수(LifeCycle)에 대해 알아보겠습니다. 생명 주기 함수는 컴포넌트의 생성부터 소멸까지의 과정에서 특정 시점에 호출되는 함수들을 의미합니다.
React 생명 주기 함수(LifeCycle)
1. 생명 주기 단계
React 컴포넌트는 크게 세 가지 생명 주기 단계로 나뉩니다:
- 마운트(Mounting): 컴포넌트가 DOM에 삽입되는 단계
- 업데이트(Updating): 컴포넌트가 갱신되는 단계
- 언마운트(Unmounting): 컴포넌트가 DOM에서 제거되는 단계
각 단계마다 호출되는 생명 주기 함수가 있습니다.
2. 마운트(Mounting)
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>;
}
}
3. 업데이트(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>;
}
}
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>;
}
}
4. 언마운트(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>;
}
}
5. 에러 처리(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>;
}
}
6. 함수형 컴포넌트와 훅(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 생명 주기 함수는 컴포넌트의 특정 시점에 실행되는 함수들로, 컴포넌트의 상태 변화에 따라 적절한 처리를 할 수 있도록 도와줍니다. 클래스형 컴포넌트에서는 생명 주기 함수를 직접 사용할 수 있고, 함수형 컴포넌트에서는 훅을 통해 동일한 기능을 구현할 수 있습니다.
오늘도 제 글을 읽어주셔서 감사합니다. 다음 시간에 더 유익한 주제로 찾아뵙겠습니다.