React 라이프사이클은 컴포넌트가 생성되고 업데이트되며, 제거되는 일련의 단계를 의미합니다. 각 단계에서 특정 메서드가 호출되며, 이를 통해 컴포넌트의 상태나 다른 작업을 수행할 수 있습니다.

마운트 단계는 컴포넌트가 처음 DOM에 삽입될 때(실행) 발생합니다. 이 단계에는 다음 네 가지 메서드가 호출됩니다.
constructor(props) {
super(props);
this.state = { count: 0 };
}
static getDerivedStateFromProps(props, state) {
if (props.someValue !== state.someValue) {
return { someValue: props.someValue };
}
return null;
}
render() {
return <div>{this.state.count}</div>;
}
componentDidMount() {
// 데이터 로드 또는 타이머 설정 등
}
업데이트 단계는 컴포넌트가 새로운 props를 받거나 상태가 변경될 때 발생합니다. 이 단계에는 다음 여섯 가지 메서드가 호출될 수 있습니다.
static getDerivedStateFromProps(props, state)
컴포넌트가 업데이트될 때도 호출됩니다.
props로부터 상태를 업데이트할 필요가 있을 때 사용됩니다.
shouldComponentUpdate(nextProps, nextState)
컴포넌트가 업데이트될지 여부를 결정합니다.
성능 최적화를 위해 사용할 수 있습니다.
shouldComponentUpdate(nextProps, nextState) {
return nextState.count !== this.state.count;
}
render()
컴포넌트의 UI를 다시 정의합니다.
getSnapshotBeforeUpdate(prevProps, prevState)
DOM이 변경되기 직전에 호출됩니다.
여기서 반환된 값은 componentDidUpdate로 전달됩니다.
getSnapshotBeforeUpdate(prevProps, prevState) {
if (prevState.count < this.state.count) {
return { scrollPosition: window.scrollY };
}
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (snapshot !== null) {
window.scrollTo(0, snapshot.scrollPosition);
}
}
언마운트 단계는 컴포넌트가 DOM에서 제거될 때 발생합니다. 이 단계에는 한 가지 메서드가 호출됩니다.
componentWillUnmount() {
// 타이머 정리 또는 구독 해제 등
}
constructor -> render -> componentDidMount ->increase function -> render -> componentDidUpdateincrease function -> render -> end -> componentDidUpdateimport React, { Component } from "react";
import { render } from "@testing-library/react";
import BoxClass from "./BoxClass";
export default class AppClass extends Component {
constructor(props) {
super(props);
// 상태를 한번에 선언
this.state = {
count: 0,
num: 1,
value: 0,
};
console.log("constructor");
}
increase = () => {
this.setState((prevState) => ({
count: prevState.count + 1,
value: prevState.value + 2,
}));
console.log("increase function", this.state);
};
componentDidMount() {
// api 콜
console.log("componentDidMount");
}
componentDidUpdate() {
console.log("componentDidUpdate", this.state);
}
render() {
console.log("render");
return (
<>
<div>state : {this.state.count}</div>
<button onClick={this.increase}>버튼</button>
{this.state.count < 3 && <BoxClass num={this.state.value} />}
</>
);
}
}
import React, { Component } from "react";
export default class BoxClass extends Component {
componentWillUnmount() {
console.log("end");
}
render() {
return (
<div>
<div>value : {this.props.num}</div>
</div>
);
}
}
요약
React 라이프사이클 메서드는 컴포넌트의 생성, 업데이트, 제거 단계에서 특정 작업을 수행할 수 있도록 도와줍니다. 이를 통해 컴포넌트의 상태를 관리하고, DOM과 상호작용하며, 성능을 최적화할 수 있습니다.
이러한 메서드는 주로 클래스 컴포넌트에서 사용되지만, 함수형 컴포넌트에서는 React 훅스(Hooks)를 사용하여 비슷한 기능을 구현할 수 있습니다. 예를 들어, useEffect 훅은 componentDidMount, componentDidUpdate, componentWillUnmount를 결합한 역할을 합니다.