React-Life Cycle

Hyun Kyung Nam·2024년 3월 29일
0

개념정리

목록 보기
8/14
post-thumbnail

LiceCycle

  • 수명주기
  • 모든 react component에 존재
  • mounting updating unmounting세가지로 나눠짐

Mount

  • DOM이 생성되고 웹 브라우저 상에 나타남

Updating

  • props/state가 바뀌었을 때 업데이트 함

Unmounting

  • 컴포넌트가 화면세어 사라질(제거될) 때

class형에서 사용되는 메서드

class형에서 mount될 때 호출되는 메서드

  • constructor
  • render
  • componenetDidMount
  • getDerivedStateFromProps

class형에서 update될 때 호출되는 메서드

  • componenetDidUpdate
  • getDerrivedStateFromProps
  • shouldComponentUpdate

class형에서 unmount될 때 호출되는 메서드

  • componenetWillUnmount

useEffect

  • 함수형컴포넌트에서는 class형과 다르게 useEffect 하나를 이용하여 특정 작업을 처리
  • 컴포넌트의 최상단에 선언
  • 형태 : useEffect(setup, dependencies?)

mount될 때 사용

  • dependencies를 비우거나 빈배열을 작성하면 됨
useEffect(setup);
//혹은
useEffect(setup, []); //

updating될 때 사용

  • dependencies(의존배열)에 참조할 값을 넣는다. 이전값과 비교하여 해당값이 변경될 떄 setup함수가 실행된다.
  • 배열형태로 작성, 각각의 값이 변경될 때마다 setup함수 실행

unmount될 때 사용

  • setup함수에 cleanup function을 return하면 된다. re-rendering시 이전 값을 가지고 cleanup function을 실행할 것이며 그다음 새로운 값으로 setup함수를 실행시킬 것이다. DOM에서 component가 제거되었을 때도 실행

사용예


import { useEffect } from 'react';
import { createConnection } from './chat.js';

function ChatRoom({ roomId }) {
  const [serverUrl, setServerUrl] = useState('https://localhost:1234');

  useEffect(() => {
    const connection = createConnection(serverUrl, roomId);
    connection.connect();//serverUrl또는 roomId가 update될 때 실행, setup코드
    return () => {
      connection.disconnect(); //unmount될 때 실행 , cleanup 코드
    };
  }, [serverUrl, roomId]); //의존 배열
  // ...
}
  • 카운터 사용예시인데 의존배열에 count를 넣어야 할 것 같지만 state 값이 변경 될 때마다 re-rendering되므로 useEffcet가 새로 불릴 것인다. 그러므로 따로 넣지 않아도 된다!
    (리액트 문서보다 신기해서 가져왔습니다)
import { useState, useEffect } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setCount(c => c + 1); // ✅ Pass a state updater
    }, 1000);
    return () => clearInterval(intervalId);
  }, []);

리액트 문서에 채팅예제가 잘 되어있는 것 같아서 나중에 참고하면 좋을 듯 합니당!

참고 : react.dev
코딩온 부트캠프 교안

0개의 댓글