⌨
Life Cycle
April 16, 2022
React Life Cycle


Mount
-
constructor: 컴포넌트의 생성자 메서드, 컴포넌트가 만들어지면 가장 먼저 실행되는 메서드constructor(props) { super(props); console.log("constructor"); } -
getDerivedStateFromProps: props를 state에 넣고 싶을때 사용static getDerivedStateFromProps(nextProps, prevState) { console.log("getDerivedStateFromProps"); if (nextProps.color !== prevState.color) { return { color: nextProps.color }; } return null; }- 앞에
static필요 - 안에서
this조회 할 수 X - 특정 객체를 반환 ⇒
state설정 O,null반환 ⇒state설정 X
- 앞에
-
render : 컴포넌트 렌더링
-
componentDidMount: 컴포넌트 첫번째 렌더링 후 호출 메서드
- 컴포넌트 화면에 나타난 상태
- DOM 속성 읽거나 변경하는 작업, DOM 사용 외부 라이브러리 연동,
axios,fetch등ajax요청 등
Update
-
getDerivedStateFromProps -
shouldComponentUpdate: 컴포넌트리렌더링결정 메서드,최적화할 때 사용 메서드shouldComponentUpdate(nextProps, nextState) { console.log("shouldComponentUpdate", nextProps, nextState); // 숫자의 마지막 자리가 4면 리렌더링하지 않습니다 return nextState.number % 10 !== 4; } -
render -
getSnapshotBeforeUpdate: 컴포넌트 변화 일어나기 전의 DOM 상태 가져와 특정 값 반환getSnapshotBeforeUpdate(prevProps, prevState) { console.log("getSnapshotBeforeUpdate"); if (prevProps.color !== this.props.color) { return this.myRef.style.color; } return null; } -
componentDidUpdate: 리렌더링 후 호출 메서드componentDidUpdate(prevProps, prevState, snapshot) { console.log("componentDidUpdate", prevProps, prevState); if (snapshot) { console.log("업데이트 되기 직전 색상: ", snapshot); } }- 3번째 파라미터로
getSnapshotBeforeUpdate에서 반환한 값 조회 할 수 있다
- 3번째 파라미터로
Unmount
-
componentWillUnmount : 컴포넌트가 화면에 사라지기 직전 호출
componentWillUnmount() { console.log("componentWillUnmount"); }