21-22/21-22 리액트 마스터
[리액트를 다루는 기술]7장 컴포넌트의 라이프사이클 메서드
도리에몽
2021. 11. 8. 15:00
728x90
1. 라이프사이클 메서드의 이해
1) 라이프 사이클 메서드의 종류(9가지)>
- Will 접두사가 붙은 메서드 : 어떤 작업을 작동하기 전에 실행되는 메서드
- Did 접두사가 붙은 메서드 : 어떤 작업을 작동한 후에 실행되는 메서드
2) 라이프 사이클의 종류
- 마운트 : 페이지에 컴포넌트가 나타남
- 업데이트 : 컴포넌트 정보를 업데이트
- 언마운트 : 페이지에서 컴포넌트가 사라짐
(1) 마운트
DOM이 생성되고 웹 브라우저상에 나타나는 것을 마운트(mount)라고 한다.

(2) 업데이트
컴포넌트가 업데이트하는 경우들
- props가 바뀔 때
- state가 바뀔 때
- 부모 컴포넌트가 리렌더링될 때
- this.forceUpdate로 강제로 렌더링을 트리거할 때

(3) 언마운트
컴포넌트를 DOM에서 제거하는 것을 언마운트(unmount)라고 한다.

2. 라이프사이클 메서드 살펴보기
1. render() 함수
render() { ... }
- 컴포넌트 모양새를 정의한다.
- 메서드 안에서 this.props와 this.state에 접근할 수 있으며, 리액트 요소를 반환한다. 요소는 div 같은 태그가 될 수도 있고, 따로 선언한 컴포넌트가 될 수 있다. 아무것도 보여주고 싶지 않다면 null값이나 false값을 반환하면 된다.
- 주의할 점은 이 메서드 안에서는 이벤트 설정이 아닌 곳에서 setState를 사용하면 안 되며, 브라우저의 DOM에 접근해서도 안된다. DOM 정보를 가져오거나 state에 변화를 줄 때는 componentDidMount에서 처리해야 한다.
2. constructor 메서드
constructor() { ... }
- 컴포넌트의 생성자 메서드로 컴포넌트를 만들 때 처음으로 실행된다.
- 이 메서드 안에서 초기 state를 정할 수 있다.
3. getDerivedStateFromProps 메서드
- props로 받아 온 값을 state에 동기화시키는 용도로 사용된다.
- 컴포넌트가 마운트 될 때와 업데이트될 때 호출된다.
static getDerivedStateFromProps(nextProps, prevState){
if(nextProps.value !== prevState.value){ //조건에 따라 특정 값 동기화
return { value: nextProps.value };
}
return null; //state를 변경할 필요가 없다면 null 반환
}
4. componentDidMount 메서드
componentDidMount() { ... }
- 컴포넌트를 만들고, 첫 렌더링을 다 마친 후 실행한다.
- 이 안에서 다른 자바스크립트 라이브러리 또는 프레임워크의 함수를 호출하거나 이벤트 등록, setTimeout, setInterval, 네트워크 요청 같은 비동기 작업을 처리하면 된다.
5. shouldComponentUpdate 메서드
shouldComponentUpdate(nextProps, nextState) { ... }
- props 또는 state를 변경했을 때, 리렌더링을 시작할지 여부를 지정하는 메서드이다.
- 이 메서드는 반드시 true 값 또는 false 값을 반환해야 한다. 컴포넌트를 만들 때 이 메서드를 따로 생성하지 않으면 기본적으로 언제나 true 값을 반환한다. false 값을 반환하면 업데이트 과정은 여기서 중지된다.
- 이 메서드 안에서 현재 props와 state는 this.props와 this.state로 접근하고, 새로 설정될 props 또는 state는 nextProps와 nextState로 접근할 수 있다.
6. getSnapshotBeforUpdate 메서드
- render에서 만들어진 결과물이 브라우저에서 실제로 반영되기 직전에 호출된다.
- 이 메서드에서 반환하는 값은 componentDidupdate에서 세 번째 파라미터인 snpashot 값으로 전달받을 수 있다.
- 주로 업데이트하기 직전의 값을 참고할 일이 있을 때 활용된다.( ex : 스크롤바 위치 유지)
getSnapshotBeforeUpdate(prevProps, prevState){
if(prevState.array !== this.state.array) {
const { scrollTop, scrollHeight } = this.list
return { scrollTop, scrollHeight };
}
}
7. componentDidUpdate 메서드
componentDidUpdate(prevProps, prevState, snapshot){ ... }
- 리렌더링을 완료한 후 실행한다. 업데이트가 끝난 직후이므로, DOM 관련 처리를 해도 무방하다.
- prevProps 또는 prevState를 사용하여 컴포넌트가 이전에 가졌던 데이터에 접근할 수 있다.
- getSnapshotBeforeUpdate에서 반환한 값이 있다면 여기서 snapshot 값을 전달받을 수 있다.
8. componentWillUnmount 메서드
componentWillUnmount() { ... }
- 컴포넌트를 DOM에서 제거할 때 실행한다.
- componentDiMount에서 등록한 이벤트, 타이머, 직접 생성한 DOM이 있다면 여기서 제거 작업을 해야 한다.
9. componentDidCatch 메서드
- 컴포넌트 렌더링 도중에 에러가 발생했을 때 애플리케이션이 먹통이 되지 않고 오류 UI를 보여 줄 수 있게 해 준다.
componentDidCatch(error, info){
this.setState({
error: true
});
console.log({error, info});
}
- error 파라미터는 어떤 에러가 발생했는지 알려준다.
- info 파라미터는 어디에 있는 코드에서 오류가 발생했는지에 대해 알려준다.
3. 라이프사이클 메서드 사용하기
1. 예제 컴포넌트 생성
import React, { Component } from 'react';
class LifeCycleSmaple extends Component {
state = {
number: 0,
color : null,
}
myRef = null; //ref를 설정할 부분
constructor(props){
super(props);
console.log('constructor');
}
static getDerivedStateFromPorps(nextProps, prevState){
console.log('getDerivedStateFromPorps');
if(nextProps.color !== prevState.color){
return{ color: nextProps.color};
}
return null;
}
componentDidMount(){
console.log('componentDidMount');
}
shouldComponentUpdate(nextProps, nextState){
console.log('shouldComponentUpdate', nextProps, nextState);
//숫자의 마지막 자리가 4면 리렌더링하지 않는다.
return nextState.umber % 10 !== 4;
}
componentWillUnmount(){
console.log('componentWillUnmount')
}
handleClick = () => {
this.setState({
number: this.state.number + 1
});
}
getSnapshotBeforeUpdate(prevProps, prevState){
console.log('getSnapshotBeforUpdate');
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>
<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 LifeCycleSmaple;
2. App 컴포넌트에서 예제 컴포넌트 사용
import React, { Component } from 'react';
import LifeCycleSmaple from './LifeCycleSmaple';
//랜덤 색상을 생성합니다.
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>
<LifeCycleSmaple color={this.state.color} />
</div>
);
}
}
export default App;



3. 에러 잡아내기
에러를 만들어보자!
import React, { Component } from 'react';
class LifeCycleSmaple extends Component {
state = {
number: 0,
color : null,
}
myRef = null; //ref를 설정할 부분
constructor(props){
super(props);
console.log('constructor');
}
static getDerivedStateFromPorps(nextProps, prevState){
console.log('getDerivedStateFromPorps');
if(nextProps.color !== prevState.color){
return{ color: nextProps.color};
}
return null;
}
componentDidMount(){
console.log('componentDidMount');
}
shouldComponentUpdate(nextProps, nextState){
console.log('shouldComponentUpdate', nextProps, nextState);
//숫자의 마지막 자리가 4면 리렌더링하지 않는다.
return nextState.umber % 10 !== 4;
}
componentWillUnmount(){
console.log('componentWillUnmount')
}
handleClick = () => {
this.setState({
number: this.state.number + 1
});
}
getSnapshotBeforeUpdate(prevProps, prevState){
console.log('getSnapshotBeforUpdate');
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}
<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 LifeCycleSmaple;
에러를 잡아주는 컴포넌트 생성
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;
에러가 발생하면 componentDidCatch 메서드가 호출되며, 이 메서드는 this.state.error 값을 true로 업데이트해 준다. 그리고 render 함수는 this.state.error 값이 true 라면 에러가 발생했음을 알려주는 문구를 보여준다.
app.js에 적용하기
import React, { Component } from 'react';
import LifeCycleSmaple from './LifeCycleSmaple';
import ErrorBoundary from './ErrorBoundary';
//랜덤 색상을 생성합니다.
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>
{this.props.missing.value}
<button onClick={this.handleClick}>랜덤 색상</button>
<ErrorBoundary>
<LifeCycleSmaple color={this.state.color} />
</ErrorBoundary>
</div>
);
}
}
export default App;
정리하기

퀴즈
1. 마운트 할 때 호출하는 메서드 중 컴포넌트를 새로 만들 때마다 호출되는 클래스 생성자 메서드는?
2. 컴포넌트가 업데이트되는 경우 총 4가지에 해당하지 않는 보기를 고르세요.
① props가 바뀔 때
② state가 바뀔 때
③ 부모 컴포넌트가 리렌더링 될 때
④ this.forceUpdate로 강제로 렌더링을 트리거할 때
⑤ 컴포넌트의 css를 바꿀 때
3. 컴포넌트를 DOM에서 제거하는 것을 뭐라고 할까?
정답 보기
더보기
1번 답 constructor
2번 답 ⑤
3번 답 언마운트(unmount)
728x90