Dev./FE
[React] componentDidMount, componentDidUpdate
인쥭
2021. 12. 28. 09:34
반응형
React.Component – React
A JavaScript library for building user interfaces
ko.reactjs.org
# 참고. 마운트시 컴포넌트 인스턴스 호출 순서
constructor() > getDerivedStateFromProps() > render() > componentDidMount()
# 참고. 업데이트시 컴포넌트 렌더링을 위한 호출 순서
getDerivedStateFromProps() > shouldComponentUpdate() > render() > getSnapshotBeforeUpdate() > componentDidUpdate()
1. componentDidMount
- 컴포넌트가 트리에 삽입된 직후에 호출
- 용도
- DOM 노드가 있어야 하는 초기화 작업
- 네트워크를 통해 데이터를 화면에 뿌려주는 경우, 요기서 수행
- 요기서 setState를 호출할 수 있지만, 주의해서 사용해야 함.
- render()가 두 번 호출되기 때문. 왠만한 경우라면 constructor에서 초기 state를 지정한다.
2. componentDidUpdate
- 갱신이 일어난 직후에 호출되지만, 최초 렌더링에서는 호출되지 않는다.
- 컴포넌트가 갱신된 경우 DOM을 조작하기 위해 활용할 수 있다.
- setState를 호출할 수 있지만, 적절한 조건문을 사용하지 않으면 무한 반복이 일어날 수 있다.