[React] Component Lifecycle (v16.3)

2022. 9. 1. 21:49·🍞 FrontEnd/React

리액트 컴포넌트는 탄생부터 죽음까지 여러 지점에서 개발자가 작업이 가능하도록

메서드를 오버 라이딩할 수 있게 해준다.

 

constructor

componentWillMount => getDerivedStateFromProps

render (최초 랜더)

componentDidMount

 

class App extends React.Component {
  state = {
    age: 39,
  };
  constructor(props) {
    super(props);
    console.log("constructor", props);
  }
  render() {
    console.log("render");
    return (
      <div>
        <h1>
          Hello {this.props.name} - {this.state.age}
        </h1>
      </div>
    );
  }
  // class component의 static 메서드로 지정해줘야함
  static getDerivedStateFromProps(nextProps, prevState) {
    console.log("getDerivedStateFromProps", nextProps, prevState);
    return {
      age: 390, // 새로운 state 설정 가능
    };
    // nextProps와 관계 없이 state가 변경돼도 이 부분이 불린다.
  }
  componentDidMount() {
    console.log("componentDidMount");
    this.interval = setInterval(() => {
      this.setState((state) => ({ ...state, age: state.age + 1 }));
    }, 1000);
  }
}
ReactDOM.render(<App name="Yejin" />, document.querySelector("#root"));

 

Component props, state 변경


1. componentWillReceiveProps => getDerivedStateFromProps

- props를 새로 지정했을 때 바로 호출된다.

- 여기서 state의 변경에 반응하지 않는다.

- 여기서 props의 값에 따라 state를 변경해야 한다면

  - setState를 이용해 state를 변경한다.

  - 그러면 다음 이벤트로 각각 가는 것이 아니라 한 번에 변경된다.

 

2. shouldComponentUpdate

- props만 변경되어도

- state만 변경되어도

- props & state 둘 다 변경되어도

- newProps와 newState를 인자로 해서 호출

- retrun type이 boolean이다.

  - true면 render

  - false면 render가 호출되지 않는다.

  - 이 함수를 구현하지 않으면, 디폴트는 true

 

3. componentWillUpdate => getSnapshotBeforeUpdate (DOM에 적용)

- 컴포넌트가 재랜더링 되기 직전에 불린다.

- 여기선 setState 같은 것을 쓰면 안 된다.

 

4. render

 

5. componentDidUpdate

- 컴포넌트가 재랜더링을 마치면 불린다.

 

let i = 0;
class App extends React.Component {
  state = { list: [] };
  render() {
    return (
      <div id="list" style={% raw %}{{ height: 100, overflow: "scroll" }}{% endraw %}>
        {this.state.list.map((i) => {
          return <div>{i}</div>;
        })}
      </div>
    );
  }
  ComponentDidMount() {
    setInterval(() => {
      this.setState((state) => ({
        list: [...state.list, i++],
      }));
    }, 1000);
  }
  // 스크롤도 같이 내려가는 거 구현
  getSnapshotBeforeUpdate(prevProps, prevState) {
    if (prevState.list.length === this.state.list.length) return null;
    const list = document.querySelector("#list");
    return list.scrollHeight - list.scrollTop;
  }
  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log(snapshot);
    if (snapshot === null) return;
    const list = document.querySelector("#list");
    list.scrollTop = list.scrollHeight - snapshot;
  }
}
ReactDOM.render(<App name="Yejin" />, document.querySelector("#root"));

 

Component 언마운트

componentWillUnmount

class App extends React.Component {
  state = {
    age: 39,
  };
  interval = null; // interval 정의
  constructor(props) {
    super(props);
    console.log("constructor", props);
  }
  render() {
    console.log("render");
    return (
      <div>
        <h1>
          Hello {this.props.name} - {this.state.age}
        </h1>
      </div>
    );
  }
  componentWillMount() {
    console.log("componentWillMount");
  }
  componentDidMount() {
    console.log("componentDidMount");
    this.interval = setInterval(() => {
      this.setState((state) => ({ ...state, age: state.age + 1 }));
    }, 1000);
  }

  componentWillReceiveProps(nextProps) {
    console.log("componentWillReceiveProps", nextProps);
  }
  shouldComponentUpdate(nextProps, nextState) {
    console.log("shouldComponentUpdate", nextProps, nextState);
    return true;
  }
  componentWillUpdate(nextProps, nextState) {
    console.log("componentWillUpdate", nextProps, nextState);
  }
  componentDidUpdate(prevProps, prevState) {
    console.log("componentDidUpdate", prevProps, prevState);
  }
  componentWillUnmount() {
    clearInterval(this.interval);
  }
}
ReactDOM.render(<App name="Yejin" />, document.querySelector("#root"));

 

Component 에러 캐치

componentDidCatch

class App extends React.Component {
  state = {
    hasError: false,
  };
  render() {
    if (this.state.hasError) {
      return <div>예상치 못한 에러가 발생했다.</div>;
    }
    return <WebService />;
  }
  componentDidCatch(error, info) {
    this.setState({ hasError: true });
  }
}

'🍞 FrontEnd > React' 카테고리의 다른 글

[React] Styled Component  (0) 2022.09.01
[React] SPA와 react-router-dom v6 되면서 바뀐점  (0) 2022.09.01
[React] Component Lifecycle (v16.3 이전)  (0) 2022.09.01
[React] Event Handling  (0) 2022.09.01
[React] Props와 State, Render함수  (0) 2022.09.01
'🍞 FrontEnd/React' 카테고리의 다른 글
  • [React] Styled Component
  • [React] SPA와 react-router-dom v6 되면서 바뀐점
  • [React] Component Lifecycle (v16.3 이전)
  • [React] Event Handling
박빵이
박빵이
2025년에도 갓생살기
  • 박빵이
    기억보다 기록
    박빵이
  • 전체
    오늘
    어제
    • 분류 전체보기 (337)
      • 🍞 FrontEnd (97)
        • HTML+CSS (4)
        • JavaScript (17)
        • TypeScript (4)
        • React (52)
        • Next.js (2)
        • Android (15)
      • 🍞 BackEnd (24)
        • Java (15)
        • Node.js (6)
        • Spring (1)
      • 🍞 Cloud & Infra (0)
        • AWS SAA (0)
        • Microsoft Azure (0)
      • 🍞 Algorithm (147)
        • C++ (4)
        • Baekjoon (41)
        • Programmers (97)
      • 🍞 Computer Science (18)
        • 운영체제 (1)
        • 데이터 통신 (6)
        • 네트워크 (6)
        • 데이터베이스 (1)
      • 🍞 대외활동 & 부트캠프 (42)
        • 삼성 청년 SW 아카데미 (1)
        • LG유플러스 유레카 (0)
        • 한국대학생IT경영학회 (1)
        • IT연합동아리 UMC (17)
        • 길벗 블로깅 멘토 (18)
        • IT연합동아리 피로그래밍 (3)
        • 개발 컨퍼런스 (2)
  • 블로그 메뉴

    • Admin
  • 링크

    • GitHub
  • 인기 글

  • 태그

    C++
    umc
    react
    level1
    위상정렬
    Java
    level2
    프로그래머스
    유니온파인드
    백준
    알고리즘
    Android
    JavaScript
    안드로이드
    Front
    길벗 블로깅 멘토링
    코딩자율학습
    길벗 블로깅 멘토
    코틀린
    map
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
박빵이
[React] Component Lifecycle (v16.3)
상단으로

티스토리툴바