생명주기 메서드와 종류
React 생명주기 메서드와 종류
개요
React 클래스 컴포넌트는 컴포넌트의 생성부터 소멸까지 다양한 생명주기 메서드를 제공합니다. 이러한 메서드는 컴포넌트가 특정 시점에 특정 작업을 수행할 수 있도록 해줍니다. 생명주기 메서드는 크게 세 가지 단계로 나눌 수 있습니다: 마운트(Mount), 업데이트(Update), 언마운트(Unmount).
생명주기 메서드 종류
마운트(Mount) 단계
컴포넌트가 DOM에 삽입될 때 호출되는 메서드들입니다.
- constructor
- 컴포넌트가 처음 생성될 때 호출됩니다. 초기 상태(state)와 클래스 메서드를 바인딩하는 데 주로 사용됩니다. ```javascript constructor(props) { super(props); this.state = { count: 0 }; }
- static getDerivedStateFromProps
컴포넌트가 마운트되기 전이나 업데이트되기 전에 호출됩니다. props로부터 파생된 state를 반환합니다.
1
2
3
4
5
6
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.someValue !== prevState.someValue) {
return { derivedState: nextProps.someValue };
}
return null;
}
- render 필수 메서드로, 컴포넌트의 UI를 정의합니다. JSX를 반환합니다.
1
2
3
render() {
return <div>{this.state.count}</div>;
}
- componentDidMount 컴포넌트가 마운트된 후에 호출됩니다. 네트워크 요청이나 이벤트 리스너 설정 등에 사용됩니다.
1
2
3
componentDidMount() {
console.log('Component did mount');
}
업데이트(Update) 단계
컴포넌트의 props 또는 state가 변경될 때 호출되는 메서드들입니다.
static getDerivedStateFromProps 마운트 단계와 동일하게, props에서 파생된 state를 반환합니다.
shouldComponentUpdate 새로운 props 또는 state를 받았을 때 렌더링을 수행할지 결정합니다. true 또는 false를 반환합니다. ```javascript shouldComponentUpdate(nextProps, nextState) { return nextProps.someValue !== this.props.someValue; }
1
2
3
4
5
6
7
8
9
10
11
12
13
3. render
마운트 단계와 동일하게, 컴포넌트의 UI를 정의합니다.
4. getSnapshotBeforeUpdate
컴포넌트가 DOM에 반영되기 직전에 호출됩니다. 반환된 값은 componentDidUpdate에 전달됩니다.
```javascript
getSnapshotBeforeUpdate(prevProps, prevState) {
if (prevProps.someValue !== this.props.someValue) {
return this.divRef.scrollHeight;
}
return null;
}
- componentDidUpdate 컴포넌트가 업데이트된 후에 호출됩니다. 네트워크 요청이나 DOM 조작 등에 사용됩니다.
1
2
3
4
5
6
7
componentDidUpdate(prevProps, prevState, snapshot) {
if (snapshot !== null) {
console.log('Snapshot:', snapshot);
}
console.log('Component did update');
}
언마운트(Unmount) 단계
컴포넌트가 DOM에서 제거될 때 호출되는 메서드입니다.
- componentWillUnmount 컴포넌트가 DOM에서 제거되기 직전에 호출됩니다. 타이머 해제, 이벤트 리스너 제거 등에 사용됩니다.
1
2
3
4
componentWillUnmount() {
console.log('Component will unmount');
}
마무리
React 클래스 컴포넌트의 생명주기 메서드는 컴포넌트의 생성, 업데이트, 제거 시점에 특정 작업을 수행할 수 있도록 도와줍니다. 이러한 메서드를 적절히 활용하면 더욱 효율적이고 안정적인 애플리케이션을 개발할 수 있습니다.
감사합니다.
This post is licensed under CC BY 4.0 by the author.
