리액트 공식 문서 정리(4) - State와 생명주기

Jessie H·2022년 9월 7일
0

react

목록 보기
5/13
post-thumbnail

** 라이프 사이클 메소드의 경우 클래스 컴포넌트에서만 해당되는 내용이기 때문에 여기에서는 클래스 컴포넌트만 다룸

** 함수 컴포넌트의 경우 Hooks부분에서 자세하게 다룰 예정


state

  • 정보를 저장하기 위한 리액트의 빌트인 객체
  • state는 변할 수 있는 객체
  • state가 변할 때 마다 컴포넌트가 리렌더링 됨

state가 변하는 경우

  • 사용자의 행동
  • 이벤트 발생
  • 네트워크 변경

출처: https://www.simplilearn.com/tutorials/reactjs-tutorial/reactjs-state


클래스 컴포넌트 state 설정하기

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

컴포넌트 라이프 사이클 메소드

Mount -> Update -> Unmount

  • 컴포넌트가 처음 DOM에 렌더링 될 때를 "Mount"라고 함
    (이 때 라이프 사이클 메소드가 호출됨)
  • 두번째 렌더링부터 "Update"라고 한다
  • 컴포넌트가 DOM에서 제거될 때를 "Unmount"라고 한다
    (유저가 다른 사이트로 이동할 때 등(navigate)의 경우)

출처: https://www.codecademy.com/learn/react-101/modules/react-102-lifecycle-methods-u/cheatsheet

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

코드출처: 리액트 공식문서

Mount

componentWillMount() -> render() -> componentDidMount()

  • Unmount시 componentDidMount() 실행

Update

componentWillReceiveProps -> shouldComponentUpdate -> componentWillUpdate -> render -> componentDidUpdate

profile
코딩 공부 기록장

0개의 댓글