최근에 React의 개념을 파헤치던중 컴포넌트의 생명주기에 대해서 공부하게 되었다.
처음에는 단순히 컴포넌트가 화면에 나타나고 사라지는 것이라고만 생각했는데, 실제로 공부해보니 훨씬 더 복잡하고 깊이있는 개념이었기에 필자가 생명주기에 대해 공부하면서 정리한 내용을 공유하고자 한다.
생명주기란?
React 컴포넌트의 생명주기는 컴포넌트가 생성되고, 업데이트되고, 제거되는 전체적인 과정을 의미한다.
이는 마치 우리가 태어나서 살아가다가 죽음을 맞이하는 것처럼, 컴포넌트도 자신만의 생애 주기를 가지고 있다.
(React에서는 이러한 각각의 단계에서 특정 코드를 실행할 수 있게 해주는 메서드들을 제공하고 있다.)
그럼 이제 자세하게 알아보자!
1. 마운팅 단계
마운팅은 컴포넌트가 처음 DOM에 렌더링되는 과정이며, 이 단계에서는 다음과 같은 메서드들이 순차적으로 실행된다.
- constructor()
- getDerivedStateFromProps()
- render()
- componentDidMount()
예시 코드를 통해 살펴보겠다.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
console.log('1. constructor 호출');
}
static getDerivedStateFromProps(props, state) {
console.log('2. getDerivedStateFromProps 호출');
return null;
}
componentDidMount() {
console.log('4. componentDidMount 호출');
}
render() {
console.log('3. render 호출');
return (
<div>
<h1>카운트: {this.state.count}</h1>
</div>
);
}
}
- 이 코드에서 constructor는 컴포넌트가 생성될 때 가장 먼저 호출되는 메서드이다. (여기서는 state를 초기화하고 있다._
- getDerivedStateFromProps는 props로 받아온 값을 state에 동기화시키고 싶을 때 사용한다.
- render는 실제 UI를 렌더링하는 메서드이며,
- componentDidMount는 컴포넌트가 실제 DOM에 마운트된 직후에 호출된다!!
2. 업데이트 단계
컴포넌트의 props나 state가 변경되면 업데이트가 발생하며, 업데이트 시에는 다음 메서드들이 순차적으로 실행된다.
- getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
이 또한 예시코드를 통해 살펴보자.
class UpdateComponent extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
console.log('2. shouldComponentUpdate 호출');
return true; // true를 반환하면 업데이트를 진행
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('4. getSnapshotBeforeUpdate 호출');
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('5. componentDidUpdate 호출');
}
render() {
console.log('3. render 호출');
return (
<div>
<h1>업데이트 예시</h1>
</div>
);
}
}
- shouldComponentUpdate는 컴포넌트가 리렌더링을 할지 말지 결정하는 메서드이다.
- getSnapshotBeforeUpdate는 변경사항이 실제 DOM에 반영되기 직전에 호출되며,
- componentDidUpdate는 업데이트가 완료된 후 호출된다.
3. 언마운팅 단계
언마운팅은 컴포넌트가 DOM에서 제거되는 과정이며, 이 단계에서는 componentWillUnmount 메서드만 호출된다.
class UnmountComponent extends React.Component {
componentWillUnmount() {
console.log('componentWillUnmount 호출');
// 컴포넌트가 제거되기 전에 필요한 정리 작업 수행
}
render() {
return <div>곧 제거될 컴포넌트</div>;
}
}
componentWillUnmount는 주로 이벤트 리스너 제거나 타이머 정리 등 cleanup 작업을 수행하는데 사용된다!
Hooks와 생명주기???!
함수형 컴포넌트에서는 useEffect Hook을 사용하여 생명주기와 유사한 기능을 구현할 수 있다!!
import React, { useEffect, useState } from 'react';
function LifecycleHooks() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('컴포넌트가 마운트됨');
return () => {
console.log('컴포넌트가 언마운트됨');
};
}, []);
useEffect(() => {
console.log('count가 업데이트됨:', count);
}, [count]);
return (
<div>
<h1>카운트: {count}</h1>
<button onClick={() => setCount(count + 1)}>증가</button>
</div>
);
}
이 코드에서 첫 번째 useEffect는 마운트와 언마운트를 담당하고,
두 번째 useEffect는 특정 값(count)의 업데이트를 감지한다!
(빈 배열([])을 의존성으로 전달하면 컴포넌트가 마운트될 때만 실행되고, 특정 값을 포함시키면 해당 값이 변경될 때마다 실행된다.)
이렇게 React의 생명주기 메서드들을 이해하고 적절히 활용하면, 컴포넌트의 동작을 더욱 섬세하게 제어할 수 있지 않을까?
특히 데이터 페칭, 이벤트 리스너 관리, 애니메이션 처리 등에서 생명주기 메서드의 활용은 필수적이라고 할 수 있을 것 같다!
'React' 카테고리의 다른 글
[React] 함수형 컴포넌트 vs 클래스형 컴포넌트 👊 (0) | 2025.02.03 |
---|---|
[React] CSR, SSR의 개념과 차이점 완벽 이해하기 👍 (1) | 2025.01.31 |
[React] npm이란? 패키지 관리자의 모든 것!!! (2) | 2025.01.29 |
[React] BrowserRouter로 SPA 라우팅 구현하기 🗺️ (0) | 2025.01.28 |
[React] Recoil로 전역 상태관리하기 🌐 (0) | 2025.01.27 |