컴포넌트의 생애 주기(Lifecycle)
컴포넌트가 생성되고, 업데이트 되며, 제거되는 전 과정을 의미한다. React에서는 컴포넌트가 어떻게 렌더링되고, 데이터가 어떻게 변화하며, 컴포넌트가 제거되는지를 관리하기 위해 생명주기 메서드를 제공한다. 컴포넌트의 생애주기는 마운팅(Mounting), 업데이트(Updating), 언마운팅(Unmounting)의 단계로 나눌 수 있다.
마운팅(Mounting)
컴포넌트가 처음 생성되어 렌더링되는 과정이다. 이 단계에서는 주로 컴포넌트가 처음 화면에 나타날 때 필요한 설정이나 초기화 작업을 처리한다.
- constructor() : 컴포넌트가 생성될 때 호출된다. 상태 초기화나 바인딩 등의 작업을 할 때 사용된다.
- componentDidMount() : 컴포넌트가 DOM에 마운트된 직후 호출된다. 주로 외부 API 호출, 이벤트 리스너 등록 등의 작업을 처리한다.
예시
클래스형 컴포넌트
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
componentDidMount() {
console.log("컴포넌트가 마운트되었습니다.");
// API 호출이나 데이터 로드 작업을 여기에 작성
}
render() {
return <h1>Count: {this.state.count}</h1>;
}
}
함수형 컴포넌트 (useEffect 사용)
import { useEffect } from 'react';
const MyComponent = () => {
useEffect(() => {
console.log("컴포넌트가 마운트되었습니다.");
// 마운트 시 작업을 여기에 작성
return () => {
console.log("컴포넌트가 언마운트됩니다.");
};
}, []); // 빈 배열을 전달하면 컴포넌트가 처음 렌더링될 때만 실행
return <h1>Hello, World!</h1>;
};
업데이트(Updating)
컴포넌트의 상태나 속성이 변경되었을 때, 컴포넌트는 다시 렌더링 된다. 이 과정을 업데이트라고 한다.
- shouldComponentUpdate(nextProps, nextState) : 컴포넌트의 리렌더링 여부를 결정한다. 성능 최적화가 필요할 때 유용하다. 기본적으로 true를 반환하여 리렌더링을 허용한다.
- componentDidUpdate(prevProps, prevState) : 컴포넌트의 업데이트 후 호출 된다. 이전 상태과 속성을 비교해 실행해야 할 작업을 처리한다.
예시
클래스형 컴포넌트
class MyComponent extends React.Component {
state = { count: 0 };
shouldComponentUpdate(nextProps, nextState) {
if (nextState.count !== this.state.count) {
return true; // 상태가 변경되면 리렌더링을 허용
}
return false; // 상태가 변경되지 않으면 리렌더링을 막음
}
componentDidUpdate(prevProps, prevState) {
console.log("컴포넌트가 업데이트되었습니다.");
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increase
</button>
</div>
);
}
}
함수형 컴포넌트(useEffect 사용)
import { useState, useEffect } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("컴포넌트가 업데이트되었습니다.");
}, [count]); // count가 변경될 때마다 실행
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
};
언마운팅(Unmounting)
컴포넌트가 더 이상 필요하지 않아 DOM에서 제거되는 과정이다. 이때 컴포넌트가 사용한 리소스, 이벤트 리스너 등을 정리해야 한다.
- componentWillUnmount() : DOM에서 제거되기 직전 호출 되어 타이머를 제거하거나 이벤트 리스너를 정리하는 등의 작업을 수행한다.
예시
클래스형 컴포넌트
class MyComponent extends React.Component {
componentWillUnmount() {
console.log("컴포넌트가 언마운트됩니다.");
// 타이머나 이벤트 리스너 제거 등의 정리 작업을 수행
}
render() {
return <h1>Goodbye!</h1>;
}
}
함수형 컴포넌트(useEffect 사용)
import { useEffect } from 'react';
const MyComponent = () => {
useEffect(() => {
return () => {
console.log("컴포넌트가 언마운트됩니다.");
// 타이머나 이벤트 리스너 제거 등의 정리 작업을 수행
};
}, []); // 빈 배열을 전달하면 컴포넌트가 언마운트될 때 실행
return <h1>Goodbye!</h1>;
};
'React' 카테고리의 다른 글
useState란? (0) | 2024.12.19 |
---|---|
useEffect란? (2) | 2024.12.19 |
DOM (0) | 2024.12.19 |
화살표 함수 (4) | 2024.12.18 |
React 기초 : 컴포넌트 (3) | 2024.12.18 |