[react] 리액트 생명주기 메서드를 이용하여 비동기 작업을 처리하는 방법은 무엇인가요?
componentDidMount
: 컴포넌트가 마운트된 직후에 호출되는 메서드로, 네트워크 요청을 보내거나 데이터를 불러오는 등의 비동기 작업을 처리하기에 적합합니다. 예를 들어, API에서 데이터를 가져와 상태를 업데이트하는 작업을 할 수 있습니다.
class MyComponent extends React.Component {
componentDidMount() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
this.setState({ data: data });
});
}
// ...
}
componentDidUpdate
: 컴포넌트의 업데이트가 일어난 직후에 호출되는 메서드로, 조건에 따라 특정 상태가 변경될 때 비동기 작업을 수행하는 데 유용합니다. 이 메서드 내에서 기존 상태와 새 상태를 비교하여 필요한 작업을 처리할 수 있습니다.
class MyComponent extends React.Component {
componentDidUpdate(prevProps, prevState) {
if (this.state.data !== prevState.data) {
// 데이터가 바뀌었을 때 처리할 작업
}
}
// ...
}
특정 상황에서 비동기 작업을 시작하고 처리하기 위해선, componentDidMount
와 componentDidUpdate
외에도 componentWillUnmount
을 이용하여 작업을 중지하거나 정리하는 등의 추가적인 처리가 필요할 수 있습니다.
참고 문헌:
- https://ko.reactjs.org/docs/react-component.html#componentdidmount
- https://ko.reactjs.org/docs/react-component.html#componentdidupdate