[React] State and Lifecycle

nothing-99·2022년 9월 7일
0

react

목록 보기
3/4
post-thumbnail

State and Lifecycle

  • component -> reusable, encapsulated
  • state -> private, fully controlled by component
  • DOM node 를 rendering 하기 위해 사용된 instance of component 가 있을 것이고 해당 UI를 수정해서 업데이트가 필요할 때 instance of component의 render() 메서드를 호출할 것이다.
    특정 DOM node 렌더링을 담당하는 instance of component가 있다고 보면 된다. 이때 (local) state, lifecycle method가 도움이 된다
  • state
    - constructor(props)를 통해 생성
  • lifecycle method

state

state는 props와 매우 비슷해 보이지만 다르다.

props는 리액트가 렌더링함수를 실행할 때 해당 컴포넌트의 인스턴스를 만나면 같이 작성된 Attribute를 props 객체에 담아서 컴포넌트의 생성자를 실행한다. 즉, 외부에서 받아온 데이터들을 props라는 객체에 담는다.

반면에 state는 props로 받아온 데이터를 이용해서 초기화 할 수도 있지만 컴포넌트 내부에서 새롭게 초기화 하는 것을 가능토록 한다. state 에 컴포넌트 내부에서만 사용될 변수(필드)를 추가해서 사용하면 된다. 또, state를 컴포넌트 렌더링 메서드에서 호출하는 다른 컴포넌트에 넘겨줄 수도 있다. (이것은 props도 마찬가지)

SetState()

state의 프로퍼티의 값을 바꾸기 위한 메서드이다.

state의 값을 직접적으로 변경하면 React는 변화를 인지하지 못해서 원하는대로 렌더링이 일어나지 않는다.

setState()를 통해 state 프로퍼티의 값을 변경하면 React는 state 변경을 인지하고 virtualDOM과 실제 DOM을 비교해서 업데이트가 필요한 부분을 찾아서 업데이트한다.

즉, setState()를 사용하지 않으면 state의 변경을 React에게 알리지 않는 것과 같다. (다른 방법이 존재할까? -> 공부하면서 발견하면 수정해야함)

-> SetState()를 통해서 state를 업데이트하자!

[[setState()]]

lifecycle method

말그대로 컴포넌트의 lifecycle과 관련된 메서드이다.

  • componentDidMount() : React가 컴포넌트의 constructor를 실행하고 render 메서드를 실행한 후에 실행하는 메서드
    - 여기서 setInterval을 설정하면 좋음.
  • componentWillUnmount() : instance of Component 와 매칭되는 DOM node가 삭제되었을 때 실행하는 메서드 ( instance of Component 와 관련된 resource들을 모두 제거하는 청소부 역할을 하는 메서드이다. )

[[lifeCycle Method]]

리액트의 특징

  • "top-down" | "unidirectional" : props는 상위 컴포넌트가 하위 컴포넌트에게 데이터를 전달할 때 사용하는데 state도 특정 컴포넌트에서 생성되서 하위 컴포넌트에게 전달될 수 있다. 상위 컴포넌트의 state가 하위 컴포넌트의 props가 되는 것.. 이때, 상위에서 하위로 데이터를 넘겨주지 하위에서 상위로 데이터를 넘겨주지 않는다.

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>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Clock />); // 실행
  1. React는 Clock Component의 constructor을 호출한다. 이때, this.props와 this.state 가 초기화된다.
  2. render 를 호출한다. 주어진 React element 에 맞게 DOM node에 새로히 업데이트를 한다. DOM node와 Component는 서로 연결된 상태라고 볼 수 있다. 즉, Component가 DOM node의 업데이트를 관리한는 것이다.
  3. componentDidMount 를 호출한다. 여기서 this.timerId를 하는 이유는 추후에 DOM node가 삭제되는 경우를 고려했기 때문이다. 삭제할 때 관련된 모든 resource를 free 시켜줘야하는데 (해제) 그때 this.timerId를 이용해서 제거할 수 있음.
  4. DOM node가 삭제될 때 React는 componentWillUnmount 를 호출한다.

Component Constructor -> render -> (DOM node 생성) -> componentDidMount -> ••• -> (DOM node 삭제) -> componentWillUnmount

참조


[[튜토리얼 - 리액트]]

#리액트#

profile
- RAYC, Vaping Ape, Bitcoin Monkeys holder

0개의 댓글