본문 바로가기

TIL

React v16 lifecycle - Mounting

728x90

해당 글은 리액트 공식 문서를 기반으로 작성하였고 React 버전 16을 기준으로 합니다.

 

리액트 16 버전의 lifecycle은 크게 4가지로 나뉩니다.

- Mounting

- Updating

- Unmounting

- Error Handling

 

전부 다 쓰면 길고 지루해질까 봐 이 글에서는 Mounting에 관련된 method만 알아봅니다.

 

Mounting은 DOM에 컴포넌트가 만들어질 때의 과정입니다.

Mounting에는 4개의 method가 있습니다.

- constructor()

- static getDerivedStateFromProps() - 이 글에선 다루지 않습니다.

- render()

- componentDidMount()

 

constructor()

마운팅 되기 전에 실행됩니다.

해당 method에서는 state를 정의하거나 event를 binding 하면 됩니다.

만약 정의할 state나 binding 할 event가 없다면 굳이 넣을 필요는 없습니다.

특히 constructor에서는 this.props가 undefined이니 관련 오류를 주의해야 합니다.

 

render()

class component에서는 필수입니다.

또한 React elements, Arrays and fragments, Portals, String and numbers, Booleans or null 중 하나를 반환해야 합니다.

 

componentDidMount()

component가 mount 되고 실행됩니다.

여기서는 백엔드에 요청을 하는 등 request를 날리시면 됩니다.

 

예제는 다음과 같습니다.

import React from 'react'

class App extends React.Component {
  constructor(props) {
    super(props)
    console.log('constructor')
    this.state = {
      a: 1
    }
  }

  render() {
    console.log('render')
    const { a } = this.state
    return (
      <div>
        React-16-lifecycle
        <p>
          a: {a}
        </p>
        <button onClick={() => {
          this.setState({
            a: a + 1
          })
        }}>
          Update Button
        </button>
      </div>
    )
  }

  componentDidMount() {
    console.log('componentDidMount')
  }
}

export default App

여기서는 맨 처음에 constructor에서 로그를 하나 찍고 state를 정의해줍니다.

그리고 render()에서는 return을 React elements로 해주고 componentDidMount에서는 로그를 하나 찍습니다.

실제 실행을 해보면 로그는 다음과 같이 찍힙니다.

 

처음에 constructor가 실행되고 render 후 mount가 됩니다.

그리고 state에 변화가 일어나면 render만 실행되는 것을 알 수 있습니다.

 

관련 예제 코드 링크

반응형