React #9 - Component Life Cycle
React 기초 · 9 / 17편
- React #1 - React 기본과 특징 + JSX
- React #2 - 컴포넌트
- React #3 - props
- React #4 - state(클래스형 컴포넌트)
- React #5 - state(함수형 컴포넌트)
- React #6 - Event
- React #7 - ref. DOM
- React #8 - 컴포넌트 반복
- React #9 - Component Life Cycle
- React #10 - Hook (useState)
- React #11 - Hook (useEffect)
- React #12 - Hook(useReducer)
- React #13 - Hook(useMemo)
- React #14 - Hook(useCallback,useRef, 로컬변수 사용)
- React #15 - 커스텀 Hook 만들기
- React #16 - 컴포넌트 스타일링 #1
- React #17 - 컴포넌트 스타일링 #2
모든 리액트 컴포넌트에는 라이프사이클(수명 주기)가 존재
렌더링되기 전 준비과정 부터 페이지에서 사라질 때 끝 나게 됩니다.
React에서 가끔 컴포넌트를 업데이트 하기 전후 혹은 불필요한 업데이트를 방지하려 할때,
컴포넌트 라이플 사이클 메서드를 사용합니다 (함수형 에서 사용하기 위해서는 Hooks를 이용 해야합니다.)
- 🔗 React - 학습 게시글 관련 · blog.naver.com
라이프 사이클 메서드 9가지 종류
- Will : 작업 시작 이전
- Did : 작업 동작 이후
-> 컴포넌트 클래스에 덮어 써 선언으로 사용 가능
라이프 사이클 종류 3가지
마운트, 업데이터, 언마운트
마운트 :DOM이 생성되고 웹 브라우저상에 나타나는 것을 뜻함
constructor : 컴포넌트를 새로 만들 때 마다 호출되는 클래스 생성자
getDerivedStateFromProps : props에 있는 값을 state에 넣을때 사용하는 메서드
render : 우리가 준비한 UI를 렌더링하는 메서드
componentDidMount : 컴포넌트가 웹 브라우저상에 나타난 후 호출 하는 메서드
업데이트
컴포넌트 업데이트 상황
1) props 변경시 -> 컴포넌트 렌더링이 실행됨
2) state 변경 시
3) 부모 컴포넌트가 리 렌더링 될 떄
4) this.forceUpdate로 강제로 렌더링을 트리거 할때
getDerivedStateFromProps : 마운트 과정에서도 호출되며 업데이트 시작전에도 호출됨
props의 변화에 따라 state에 변화를 주고 싶을 떄 사용
shouldComponentUpdate : 컴포넌트가 리렌더링을 해야 할지 말아야 할지를 결정하는 메서드
true : 렌더링 진행 (라이플 사이클 메서드 진행)
false : 렌더링 중단
this.forceUpdate() 함수 호출 : shouldComponentUpdate 생략후 렌더링 진행
render : 컴포넌트 렌더링
getSnapshotBeforeUpdate : 컴포넌트 변화를 DOM에 반영하기로 바로 직전에 호출
componentDidUpdate : 컴포넌트의 업데이트 작업이 끝난 후 호출하는 메서드
언마운트 : 마운트 반대 과정
componentWillUnmont : 컴포넌트가 웹 브라우저상에서 사라지기 전에 호출 하는 메서드
매서드 분석
render 함수
컴포넌트 모양을 정의 하는 함수
this.props / this.state 접근 및 리액트 요소 반환 (요소는 div 태그 혹은 사용자 컴포넌트 tag)
주의 사항
이벤트 설정이 아닌곳에서 setState를 사용 금지
브라우저의 DOM접급 금지
(DOM 정보 / state 변화시 componentDidMount 처리)
constructor
이것은 컴포넌트의 생성자 메서드로 컴포넌트를 만들 때 처음으로 실행 됩니다.
이 메서드 에서는 초기 state를 정의 할수 있습니다.
getDerivedStateFromProps
리액트 v16.3 이후 새로 만든 라이프사이클 매서드
props 가 받은 값을 state와 동기화 시키기 위해 사용, (컴포넌트가 마운트 될때와 업데이트 될때 호출 됨)
static getDerivedStateFromProps(nextProps, prevState){
if(nextProps !== prevState.value){
return { value : nextProps.value}
}
return null
}
componentDidMount
컴포넌트를 만들고, 첫 렌더링을 마친 후 실행
다른 JS 라이브러리, 프레임워크 함수, 이벤트 등록, setTimeout, setInterval, 네크워크 요청 같은 비동기 작업 처리
shouldComponentUpdate
props 또는 state 변경시, 리렌더링을 시작 여부 지정 (true 또는 false 반환)
컴포넌트 내 비 선언시, 항상 true 반환 (false 반환시 업데이트 중단)
접근 가능 데이터 변수
기존 데이터 : this.props / this.state
변환 데이터 : nextProps / nextState
getSnapshotBeforeUpdate
리액트 v16.3 이후 만든 매서드
render에서 만든 결과가 브라우저에 반영되기 직전 호출
반환 값은 componentDidUpdate의 snapshot 으로 전달 받음 (업데이전 직전 값을 참고 할때 사용 ex : 스크롤바 유지)+
getSnapshotBeforeUpdate(prevProps, prevState){
if(prevState.array !== this.state.array){
const {scrollTop, scrollHeight} = this.list
return {scrollTop, scrollHeight};
}
}
componentDidUpdate
리렌더링 완료후 수행, 업데이트 직후라 DOM 관련 처리 가능
prevProps 또는 prevState 를 사용, 이전 데이터 접근 가능
getSnapshotBeforeUpdate의 반환 값이 있다면 snapshot 값을 전달 받을수 있음
componentWillUnmonunt
컴포넌트를 DOM에서 제거 할때 실행 componentDidMount에서 등록한 이벤트, 타이머, 생성한 DOM이 있을 경우
여기서 제거 해야함
componentDidCatch
리액트 v16 새로 도입된 메서드, 컴포넌트 렌더링 도중 에러 발생시 오류 UI를 보게 해줌
error : 에러 내용
info : 에러 발생 코드 위치
conponentDidCatch(error, info){
this.setState({
error:true
});
console.log({error, info});
}
* 컴포넌트 스스로의 에러는 찾지 못하고 this.props.children으로 전달 되는 컴포넌트에서 발생 되는 에러만 검출 가능함
Method 구현
총 3곳의 코드를 수정 해야 하며, 2개의 컴포넌트를 생성 해야 합니다.
LifeCycleSample.js
import React, {Component} from 'react';
import test from '../'
class LifeCycleSample extends Component {
state ={
number : 0,
color : null,
}
myRef = null;
constructor(props){
super(props);
console.log('constructor');
}
static getDerivedStateFromProps(nextProps, prevState){
console.log('#1 getDerivedStateFromProps');
if(nextProps.color !== prevState.color){
return {color : nextProps.color};
}
return null;
}
componentDidMount(){
console.log('componentDidMount');
}
shouldComponentUpdate(nextProps, nextState){
console.log('shouldComponentUpdate',nextProps,nextState);
return nextState.number % 10 !==4;
}
componentWillUnmount() {
console.log('componentWillUnmount');
}
handleClick = ()=>{
this.setState({
number:this.state.number +1
});
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('getSnapshotBeforeUpdate');
if(prevProps.color !== this.props.color){
return this.myRef.style.color;
}
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('componentDidUpdate', prevProps, prevState);
if(snapshot){
console.log('업데이트 되기 직전 색상',snapshot);
}
}
render() {
console.log('render');
const style ={
color:this.props.color
};
return (
<div>
{this.props.missing.value} // Error를 발생 시키기 위해 고의로 추가된 코드 (제거시 에러 미 발생)
<h1 style={style} ref={ref=> this.myRef=ref}>
{this.state.number}
</h1>
<p>color:{this.state.color}</p>
<button onClick={this.handleClick}>
더하기
</button>
</div>
);
}
}
export default LifeCycleSample;
ErrorBoundary.js
import React, {Component} from 'react';
class ErrorBoundary extends Component {
state ={
error : false
};
componentDidCatch(error, info){
this.setState({
error:true
});
console.log({error,info})
}
render() {
if(this.state.error) return <div>에러가 발생했습니다.</div>;
return this.props.children;
}
}
export default ErrorBoundary;
App.js
import React, { Component } from 'react'
import LifeCycleSample from "./reactStudy/LifeCycleSample";
import ErrorBoundary from "./reactStudy/ErrorBoundary";
import './App.css'
function getRandomColor(){
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
class App extends Component{
state = {
color : '#000000'
}
handleClick = () =>{
this.setState({
color:getRandomColor()
});
}
render(){
return(
<div>
<button onClick={this.handleClick}>랜덤색상</button>
<ErrorBoundary>
<LifeCycleSample color={this.state.color}/>
</ErrorBoundary>
</div>
);
}
}
export default App;
LifeCycleSample 의 {this.props.missing.value} 부분을 주석 한뒤 나오는 정상적 출력 결과


주석 부분을 복원 하고 실행하면 Error가 발생 하며, 해당 창을 닫으면 아래와 같이 에러가 발생했다는 정보가 출력 됨

댓글
이름만 적고 남길 수 있어요