티스토리 뷰

웹개발(프론트)/React

life Cycle

수달찌 2021. 3. 31. 21:05

목차

     

    react의 hook에 대해 정리할려 했는데,

    정리할려하니 life Cycle에 대하여 서술한 뒤 정리하여야

    처음보는사람이 이해하기 쉬울 것 같아

    먼저 적게되었다.

     

    life Cycle

    생명주기 라는 뜻으로

    코드를 브라우저로 출력하는 랜더링 과정

    진행될때의 순서를 말한다.

     

     

    React Lifecycle Methods diagram

    Fully interactive and accessible React Lifecycle Methods diagram.

    projects.wojtekmaj.pl

    React 공식 홈페이지의 링크를 타면

    정리가 잘 된 사이트를 볼 수 있다.

     

    우리가 자주 쓰는 생명주기는 과정 끝의

    • componentDidMount
    • componentDidUpdate

    이 두가지이다.

     

    ComponentDidMount

    처음 컴포넌트가 실행될때Mount라 한다.

    이때 props(인자), state(해당 데이터가 변경될때마다 렌더링된다.)

    를 저장하는 중이라 이과정에서 변경할 수 없다.

     

    주로 api데이터를 불러올때 쓴다.

    (페이지를 만드는 과정이니 데이터를 가져오는 작업이 많다.)

     

    import React, { Component } from 'react';
    
    export default class App extends Component {
      componentDidMount() {
        console.log('mount');
      }
    
      render(){
        return (
          <>
            <h1>Hello</h1>
            {console.log("render")}
          </>
        )
      }
    }

    해당 이미지의 설명과 같이

    render가 출력 된 다음,

    componentDidMount가 나온다.

     

    ComponentDidUpdate

    해당과정은

    state가 변경되거나,

    강제 업데이트함수 forceUpdate(),

    새로운 인자가 들어왔을때 실행된다.

     

    이는 맨 처음 페이지가 생성될때는 제외임으로 기억하자.

    import React, { Component } from 'react';
    
    export default class App extends Component {
    
      state = {
        count : 0,
      };
    
      componentDidMount() {
        console.log('mount');
      }
    
      componentDidUpdate() {
        console.log('update');
      }
    
      handleClick = () => {
        this.setState({ count: this.state.count+1 });
      }
    
      render(){
        return (
          <>
            <button onClick={this.handleClick}>{this.state.count}</button>
            {console.log("render")}
          </>
        )
      }
    }

    state에 count 생성뒤

    0으로 초기화한다.

     

    그다음, button을 누를때마다

    handleClick함수가 발동하여, state의 count를 1씩 증가하게 만들었다.

    이때 state가 변경되어 업데이트 됨으로

    componentDidUpdate 함수가 실행 될 것이다.

    맨처음 사이트를 새로고침 하였을때

    componentDidMount 함수가 실행되고,

    버튼을 누름으로써 update될때마다 render가 된뒤,

    componentDidUpdate실행된다.

    '웹개발(프론트) > React' 카테고리의 다른 글

    useEffect  (0) 2021.04.02
    Hooks / useState  (0) 2021.04.01
    styled component  (0) 2021.03.25
    react-router  (0) 2021.03.22
    Switch 이쁘게 쓰기 enum  (0) 2021.03.19
    댓글
    최근에 올라온 글
    최근에 달린 댓글
    Total
    Today
    Yesterday
    링크
    «   2025/03   »
    1
    2 3 4 5 6 7 8
    9 10 11 12 13 14 15
    16 17 18 19 20 21 22
    23 24 25 26 27 28 29
    30 31
    글 보관함