React 생명주기

fe_sw·2022년 8월 1일
0

React

목록 보기
4/10
post-thumbnail

리액트 컴포넌트에는 라이프사이클(수명 주기)이 존재한다.
컴포넌트의 수명은 페이지에 렌더링되기 전인 준비과정에서 시작하여 페이지에서 사라질 때끝난다.

컴포넌트를 처음으로 렌더링 할 때, 어떤 작업을 처리해야하거나 컴포넌트를 업데이트하기 전후로
어떤 작업을 처리해야 할 수도 있고, 불필요한 업데이트를 방지해야 할 수도 있다.

생명주기는 Mounting, Updating, Unmounting로 크게 나뉜다.

이러한 경우들에 컴포넌트의 라이프사이클 메서드를 사용한다.

  • wll 접두사가 붙은 메서드 👉 어떤 작업을 작동하기 전에 실행
  • did 접두사가 붙은 메서드 👉 어떤 작업을 작동한 후에 실행
  • 라이프 사이클 메서드는 총 9가지 이다.

mounting: DOM이 생성되고 웹 브라우저상에 나타나는 것

render() 메소드는 항상 호출되야하고, 다른 메소드들은 선택적으로 호출 될 수 있다.

constructor


class Header extends React.Component {
  constructor(props) {
    super(props)
    this.state = { favoritecolor: 'red' }
  }
  render() {
    return <h1>My Favorite Color is {this.state.favoritecolor}</h1>
  }
}

ReactDOM.render(<Header />, document.getElementById('root'))

constructor() 메소드는 컴포넌트가 초기화될 때 다른 어떤 메소드보다 먼저 호출되며,
state 와 다른 초기 값들을 세팅한다.

constructor() 메소드는 props 라고도 불리며, super(props) 를 가장 먼저 호출해야 한다. super(props) 는 부모의 constructor 메소드를 초기화하고, 부모로 부터 상속받은 메소드들을 컴포넌트로 하여금 사용할 수 있도록 해준다.

getDerivedStateFromProps


class Header extends React.Component {
  constructor(props) {
    super(props)
    this.state = { favoritecolor: 'red' }
  }
  static getDerivedStateFromProps(props, state) {
    return { favoritecolor: props.favcol }
  }
  render() {
    return <h1>My Favorite Color is {this.state.favoritecolor}</h1>
  }
}

ReactDOM.render(<Header favcol="yellow" />, document.getElementById('root'))

getDerivedStateFromProps() 메소드는 DOM에서 요소들이 랜더링 되기 직전에 호출된다.
최초의 props 에 기반한 state 객체를 저장한다.state 를 인자로 받고, state 가 변하면 객체를 반환한다.

render


class Header extends React.Component {
  render() {
    return <h1>This is the content of the Header component</h1>
  }
}

ReactDOM.render(<Header />, document.getElementById('root'))

render() 메소드는 필수값이며, DOM에 HTML을 표현해준다.

componentDidMount


class Header extends React.Component {
  constructor(props) {
    super(props)
    this.state = { favoritecolor: 'red' }
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({ favoritecolor: 'yellow' })
    }, 1000)
  }
  render() {
    return <h1>My Favorite Color is {this.state.favoritecolor}</h1>
  }
}

ReactDOM.render(<Header />, document.getElementById('root'))

componentDidMount() 메소드는 컴포넌트가 랜더링된 직 후에 호출된다.
이미 DOM에 위치한 컴포넌트를 필요로 하는 구문을 사용하는 곳이다.


Updating: 컴포넌트가 업데이트 할 때를 의미

컴포넌트는 상태나 props가 변경될 때 마다 업데이트 된다

5가지 내장 메소드가 있고, 컴포넌트가 업데이트 되면 순서대로 실행된다.

getDerivedStateFromProps


class Header extends React.Component {
  constructor(props) {
    super(props)
    this.state = { favoritecolor: 'red' }
  }
  static getDerivedStateFromProps(props, state) {
    return { favoritecolor: props.favcol }
  }
  changeColor = () => {
    this.setState({ favoritecolor: 'blue' })
  }
  render() {
    return (
      <div>
        <h1>My Favorite Color is {this.state.favoritecolor}</h1>
        <button type="button" onClick={this.changeColor}>
          Change color
        </button>
      </div>
    )
  }
}

ReactDOM.render(<Header favcol="yellow" />, document.getElementById('root'))

update 단계에서 getDerivedStateFromProps 메소드가 호출된다.
이 메소드는 컴포넌트가 업데이트 될 때 제일 먼저 호출되는 메소드이다.

초기 props에 기반한 state 가 저장되는 곳이다.

shouldComponentUpdate


class Header extends React.Component {
  constructor(props) {
    super(props)
    this.state = { favoritecolor: 'red' }
  }
  shouldComponentUpdate() {
    return false
  }
  changeColor = () => {
    this.setState({ favoritecolor: 'blue' })
  }
  render() {
    return (
      <div>
        <h1>My Favorite Color is {this.state.favoritecolor}</h1>
        <button type="button" onClick={this.changeColor}>
          Change color
        </button>
      </div>
    )
  }
}

ReactDOM.render(<Header />, document.getElementById('root'))

shouldComponentUpdate() 메소드는 React가 랜더링을 계속해야하는지 마는지에 대한 Boolean 값을 반환한다.
기본 값은 true이다.

render

컴포넌트가 업데이트 되면 역시 render() 도 호출된다. 새로운 변경점들을 갖고 리랜더링 된다.

getSnapshotBeforeUpdate


class Header extends React.Component {
  constructor(props) {
    super(props)
    this.state = { favoritecolor: 'red' }
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({ favoritecolor: 'yellow' })
    }, 1000)
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    document.getElementById('div1').innerHTML =
      'Before the update, the favorite was ' + prevState.favoritecolor
  }
  componentDidUpdate() {
    document.getElementById('div2').innerHTML =
      'The updated favorite is ' + this.state.favoritecolor
  }
  render() {
    return (
      <div>
        <h1>My Favorite Color is {this.state.favoritecolor}</h1>
        <div id="div1"></div>
        <div id="div2"></div>
      </div>
    )
  }
}

ReactDOM.render(<Header />, document.getElementById('root'))

getSnapshotBeforeUpdate() 메소드는 업데이트 되기 전의 props와 state에 접근할 수 있다.
즉, update 이후에도 update 이전의 값들을 확인할 수 있다는 것을 의미한다.

만약 getSnapshotBeforeUpdate() 메소드가 존재하면, componentDidUpdate() 메소드도 포함해야 한다. 그렇지 않으면 에러가 발생한다.

componentDidUpdate


class Header extends React.Component {
  constructor(props) {
    super(props)
    this.state = { favoritecolor: 'red' }
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({ favoritecolor: 'yellow' })
    }, 1000)
  }
  componentDidUpdate() {
    document.getElementById('mydiv').innerHTML =
      'The updated favorite is ' + this.state.favoritecolor
  }
  render() {
    return (
      <div>
        <h1>My Favorite Color is {this.state.favoritecolor}</h1>
        <div id="mydiv"></div>
      </div>
    )
  }
}

ReactDOM.render(<Header />, document.getElementById('root'))

componentDidUpdate() 메소드는 컴포넌트가 DOM에서 update된 후에 호출된다.


Unmounting: 컴포넌트를 DOM에서 제거하는 것

componentWillUnmount

컴포넌트가 DOM에서 제거되기 직전에 호출되는 메소드이다.

0개의 댓글