React

React STEP 7 - 생명주기 함수

2025. 2. 6. 17:48
728x90

⭐ 생명주기 함수

  • React 에서 생명주기란, 컴포넌트의 생성, 변경, 소멸 과정을 뜻합니다.

1. 생명주기 함수 사용하기

  • render() 사용하기
    - render() 함수는 return 되는 HTML 형식의 코드를 화면에 그려주는 함수, 화면 내용이 변경되어야 할 시점에 자동 호출
class LifeCycle extends React.Component {
  render() {
    let h2Style= {
      fontSize: 16,
      fontWeight: "normal"
    };

    console.log("3, render()");

    return (
      <h2 style={h2Style}>This is Render Function</h2>
    )
  }
}

class App2 extends React.Component {
  render() {
    let h1Style= {
      fontWeight: "normal"
    }
    return (
      <div>
        <h1 style={h1Style}>React Example</h1>
        <LifeCycle></LifeCycle>
      </div>
    );
  }
}

root.render (
  <App2></App2>
)
  • constructor(props)
    - 컴포넌트 내부에서 사용되는 state를 선언하고, 부모 객체에서 전달받은 props를 초기화 할때 사용합니다.
    - super(props) 함수는 가장 상위에 호출해야 합니다.
class LifeCycle2 extends React.Component {
  constructor(props){
    super(props);
    console.log("1, constructor()");
  }
  render(){
    let h2Style={
        fontSize: 16,
        fontWeight: "normal"
    };
    console.log("3. render()");
    return(
        <h2 style={h2Style}>This is Render Function.</h2>
    );
  }
}

class App2 extends React.Component {
render(){
    let h1Style={
        fontWeight: "normal"
    };
    return(
        <div>
            <h1 style={h1Style}>React Example</h1>
            <LifeCycle2 />
        </div>
    );
  }
}
  • getDerivedStateFromProps(props, state)
    - 컴포넌트가 새로운 props를 받게 되었을 때, state를 변경해 줍니다.
    - 상위 컴포넌트에서 전달한 propsValue props를 props.propsValue로 접근해 값을 가져올 수 있습니다.
class LifeCycle3 extends React.Component {
  constructor(props) {
    super(props);

    console.log("1, constructor()");
    console.log(props);
  }

  static getDerivedStateFromProps(props, state) {
    console.log("2. getDerivedStateFromProps() : "+props.propValue)
    console.log(props);
    console.log(state)

    return {};
  }

  render(){
    let h2Style={
        fontSize: 16,
        fontWeight: "normal"
    };
    console.log("3. render()");
    return(
        <h2 style={h2Style}>This is Render Function.</h2>
    );
  }

}

class App3 extends React.Component {
  render() {
    let h1Style= {
      fontWeight: "normal"
    };

    return (
      <div>
        <h1 style={h1Style}>Hello React!</h1>
        <LifeCycle3 propValue="formApp"></LifeCycle3>
      </div>
    )
  }
}

root.render(
  <App3></App3>
)
  • componentDidMount() 
    - 함수들 중 가장 마지막으로 실행됩니다.
    - 화면이 모두 그려진 후에 실행되어야 하는 이벤트 처리, 초기화 등 가장 많이 활용되는 함수입니다.
class LifeCycle4 extends React.Component {
  constructor(props) {
    super(props);

    console.log("1, consturctor()");
    console.log(props);
  }

  static getDerivedStateFromProps(props, state) {
    console.log("2, getDerivedStateFromProps() : " + props.propValue);

    return {template: props.propValue};
  }

  componentDidMount() {
    console.log("4, componentDidMount()");
    console.log("5, template : " + this.state.tempState);
    console.log(this.state);
  }

  render() {
    let h2Style= {
      fontSize: 16,
      fontWeight: "normal"
    };

    console.log("3, render()");

    return (
      <h2 style={h2Style}>This is Render Function</h2>
    )
  }
}

class App4 extends React.Component {
  render() {
    let h1Style= {
      fontWeight: "normal"
    };

    return(
      <div>
        <h1 style={h1Style}>Hello React</h1>
        <LifeCycle4 propValue="fromApp"></LifeCycle4>
      </div>
    )
  }
}

root.render (
  <App4></App4>
)
  • shouldComponentUpdate()
    - 컴포넌트의 변경 과정에 속합니다.
    - shouldComponentUpdate()는 boolean 유형의 데이터를 반환하는데, return 값이 true일 경우에는 
    render() 함수를 한 번 더 호출합니다.
     - shouldComponentUpdate() 함수의 반환 값에 따라 render() 함수를 재실행할 수 있다는 점을 
    이용하면, props나 state 값이 변경될 때 화면을 다시 그리며 제어할 수 있습니다
class Lifecycle5 extends React.Component {
  constructor(props){
      super(props);
      this.state={};
      console.log("1. constructor()");
      console.log(props);
  }
  static getDerivedStateFromProps(props, state){
      console.log("2. getDerivedStateFromProps() : "+props.propsValue);
      return {tempState1: props.propsValue};
  }
  shouldComponentUpdate(){
      console.log("6. shouldComponentUpdate()");
      return true;
  }
  componentDidMount(){
      console.log("4. componentDidMount()");
      console.log("5. tempState1 : "+this.state.tempState1);

      this.setState({tempstate2: true});
  }
  render(){
      let h2Style={
          fontSize: 16,
          fontWeight: "normal"
      };
      console.log("3. render()");
      return(
          <h2 style={h2Style}>This is Render Function.</h2>
      );
  }
}
class App5 extends React.Component {
  render(){
      let h1Style={
          fontWeight: "normal"
      };
      return(
          <div>
              <h1 style={h1Style}>Hello React</h1>
              <Lifecycle5 propsValue="fromApp" />
          </div>
      );
  }
}

root.render(
  <App5 />
)
  • 콘솔 결과 

728x90
저작자표시 비영리 변경금지 (새창열림)

'React' 카테고리의 다른 글

React STEP 9 - EcmaScript6 문법 - 2  (1) 2025.02.07
React STEP 8 - EcmaScript6 문법 - 1  (1) 2025.02.07
React STEP 6 - 컴포넌트 이해  (0) 2025.02.06
React STEP 5 - 컴포넌트 스타일 2  (0) 2025.02.06
React STEP 4 - 컴포넌트 스타일 1  (0) 2025.02.06
'React' 카테고리의 다른 글
  • React STEP 9 - EcmaScript6 문법 - 2
  • React STEP 8 - EcmaScript6 문법 - 1
  • React STEP 6 - 컴포넌트 이해
  • React STEP 5 - 컴포넌트 스타일 2
IT의 큰손
IT의 큰손
IT계의 큰손이 되고 싶은 개린이의 Log 일지
Developer Story HouseIT계의 큰손이 되고 싶은 개린이의 Log 일지
IT의 큰손
Developer Story House
IT의 큰손
전체
오늘
어제
  • 분류 전체보기 (457)
    • 정보처리기사 필기 (18)
    • 정보처리기사 실기 (12)
    • 정보처리기사 통합 QUIZ (12)
    • 빅데이터 (11)
    • 안드로이드 (11)
    • 웹페이지 (108)
    • 자바 (49)
    • SQLD (3)
    • 백준 알고리즘 (76)
    • 데이터베이스 (41)
    • 깃허브 (2)
    • Library (14)
    • Server (31)
    • 크롤링&스크래핑 (3)
    • Spring (23)
    • Vue.js (13)
    • React (27)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Developer Stroy House

인기 글

태그

  • ajax
  • 웹개발자
  • java
  • jquery
  • it
  • IT자격증
  • DBA
  • 백엔드
  • JavaScript
  • jsp
  • 웹개발
  • 자바
  • css
  • DB
  • 데이터베이스
  • 웹페이지
  • 정보보안전문가
  • React
  • 개발자
  • IT개발자
  • 코딩테스트
  • 정보처리기사필기
  • 정보처리기사
  • 알고리즘
  • 앱개발자
  • 프론트엔드
  • html
  • 백준
  • 개발블로그
  • IT자격증공부

최근 댓글

최근 글

Designed By hELLO
IT의 큰손
React STEP 7 - 생명주기 함수
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.