[React] State와 Lifecycle

김호중·2024년 4월 3일
0

React

목록 보기
8/15

State 공식문서

react의 컴포넌트들은 여러 interaction에 대해 동작을 감지하고 기억하며 적용하는 것이 필요하다. 입력을하고, 버튼을 클릭하며, 제출을 하는 등의 동작이다.
이러한 것들에대한 '기억''State'라고 말한다.

React에서는 단순히 기억만을 고려하지 않는다. 사용자에게 보여지는 컴포넌트(UI)의 Render이 필요하다.

useState

따라서 State와 Render을 연결하기위해 useState라는 훅을 제공한다.


Lifecycle 공식문서

리액트 컴포넌트의 Lifecyle은 총 3단계를 갖고있다.

  1. 생성(mounting): 해당 컴포넌트가 스크린에 추가될 때
  2. 업데이트(updating): 해당 컴포넌트가 prop 또는 state를 전달받을 때(usually in response to an interaction)
  3. 제거(unmounting): 해당 컴포넌트가 스크린에서 제거될 때

이를 제어하기 위해

  • 클래스형 컴포넌트에서는 -> 라이프사이클 메서드를 사용한다.
  • 함수형 컴포넌트에서는 -> React Hook을 사용한다.

(현재 React에서는 함수형 컴포넌트 사용을 지향하기 때문에 이에 대해서만 다루도록 하겠다.)

useEffect

Lifecycle을 제어하는 hook은 공식문서에서 Effect라고 불리는 useEffect이다. (참고:Effect 사용 관련 공식문서)

간단한 예제를 통해 위 3과정을 살펴보면 아래와 같다.

function ChatRoom({ roomId /* "general" */ }) {
  useEffect(() => {
    const connection = createConnection(serverUrl, roomId); // Connects to the "general" room
    connection.connect();
    return () => {
      connection.disconnect(); // Disconnects from the "general" room
    };
    // ...
  • 해당 컴포넌트에 대해 아래와 같은 동작이 일어난다면

    1. ChatRoom 컴포넌트(스크린)으로 이동
    2. roomId = 'general'
    3. roomId = 'travel'
    4. roomId = 'music'
    5. 다른 컴포넌트(스크린)으로 이동
  • ChatRoom의 Lifecycle

    1. ChatRoom mounted with roomId set to "general"
    2. ChatRoom updated with roomId set to "travel"
    3. ChatRoom updated with roomId set to "music"
    4. ChatRoom unmounted
  • Lifecycle동안의 Effect

    1. Your Effect connected to the "general" room
    2. Your Effect disconnected from the "general" room and connected to the "travel" room
    3. Your Effect disconnected from the "travel" room and connected to the "music" room
    4. Your Effect disconnected from the "music" room
profile
개발의 흔적을 남기고 쌓아가기 위한 일기장

0개의 댓글