


Mounting 아래 메서드들은 컴포넌트의 인스턴스가 생성되어 DOM 상에 삽입될 때에 순서대로 호출됩니다.
constructor()React.Component를 상속한 컴포넌트의 생성자를 구현할 때에는 다른 구문에 앞서 super(props)를 호출해야 합니다. 그렇지 않으면 this.props가 생성자 내에서 정의되지 않아 버그로 이어질 수 있습니다.constructor() 내부에서 setState()를 호출하면 안 됩니다. 컴포넌트에 local state가 필요하다면 생성자 내에서 this.state에 초기 state 값을 할당하면 됩니다.static getDerivedStateFromProps()render()React element, array와 Fragment, Portal, 문자열과 숫자, Booleans or null or undefined 중 하나를 반환해야 합니다.componentDidMount()subscriptions가 이루어졌다면 componentWillUnmount()에서 unsubscribe해야 합니다.Updating props 또는 state가 변경되면 갱신이 발생합니다. 아래 메서드들은 컴포넌트가 다시 렌더링될 때 순서대로 호출됩니다.
static getDerivedStateFromProps()shouldComponentUpdate()render()getSnapshotBeforeUpdate()componentDidUpdate()setState()를 즉시 호출할 수도 있지만, 조건문으로 감싸지 않으면 무한 반복이 발생할 수 있다는 점에 주의해야 합니다.Unmounting 컴포넌트가 DOM에서 제거될 때 실행됩니다.
componentWillUnmount()componentDidMount() 내에서 생성된 데이터 unsubscribing 등 필요한 모든 정리 작업을 수행합니다.setState()를 호출하면 안 됩니다.import React, { Component } from 'react';
class ExampleComponent extends Component {
constructor(props) { // 컴포넌트가 생성될 때 호출
super(props);
this.state = { count: 0 }; // 초기 상태 설정
this.handleClick = this.handleClick.bind(this); // 메서드 바인딩
}
static getDerivedStateFromProps(props, state) { // 컴포넌트의 초기 상태를 설정하거나 프로퍼티에 따라 상태를 업데이트할 필요가 있을 때 호출
return null; // 새로운 state 리턴
}
componentDidMount() { // 컴포넌트가 마운트되고 DOM에 삽입된 후 실행
// 외부 데이터 불러오기 혹은 이벤트 리스너 등록
}
shouldComponentUpdate(nextProps, nextState) { // 컴포넌트의 업데이트 여부를 결정
return nextState.count !== this.state.count; // count 상태가 변경되었을 때만 업데이트가 발생
}
getSnapshotBeforeUpdate(prevProps, prevState) {
// render()가 호출된 후, DOM이 업데이트되기 전에 호출될 작업
}
componentDidUpdate(prevProps, prevState, snapshot) {
// 컴포넌트의 업데이트가 완료된 후에 호출될 작업
}
componentWillUnmount() {
// 컴포넌트가 DOM에서 제거되기 전의 호출될 작업
// 이벤트 리스너를 제거 혹은 다른 정리 작업
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() { // UI 업데이트
console.log('render');
return (
<div>
<h1>{this.props.title}</h1>
<p>You clicked {this.state.count} times</p>
<button onClick={this.handleClick}>Click me</button>
</div>
);
}
}
export default ExampleComponent;
useEffect()는 함수형 컴포넌트에서 Side Effect를 처리하기 위한 React Hook입니다.React hookuseEffect(() => {
// side effect code
return () => {
// cleanup function
}
}, dependency list);Side EffectFetching data from a serverManipulating the DOMSubscribing to eventsSetting timersLoading and unloading librariesManaging statedependency listcleanup functionSide Effect에서 발생한 리소스를 정리하거나 해제하는 역할을 합니다.useEffect()의 생명 주기는 useEffect() 콜백 함수가 실행될 때 작업들을 처리합니다.dependency array의 내용이 변경될 때마다 발생할 수 있습니다.useEffect()를 사용할 때는 컴포넌트의 관점(마운트, 업데이트 또는 마운트 해제 방법)이 아닌 각 개별 효과의 관점(동기화 시작 및 중지 방법)에서 생각해야합니다.Reference