본문 바로가기

TIL✨

react-component의 실행 순서 TIL

프로젝트 중에 비동기처리로 data가 오기전에 먼저 렌더링이 되어서 undefined가 되었던 적이 많은데 그래서 예외처리라던가,

isLoading, 옵셔널 체이닝 등을 써주었다. 

그래서 튜터님이 가르쳐주신 component실행 순서를 기록해보려고한다.


component lifeCycle

그냥 쉽게 말해서 컴포넌트가 실행되었을때를 mounting되었다라고 하고 내가 다른 페이지이동을해서 그 컴포넌트를 벗어나면 unmounting이라고 한다.

그리고 중간에 있는 updating은 props전달, state변경으로 인해 일어난다.

 

componentDidMount , componentDidUpdata , componentWillUnmount 이 세가지는 useEffect로 구현이 가능하다.

 

내가 착각하고 있었던 점은 useEffect가 컴포넌트 실행 시 제일 먼저 실행되는 줄 알았다.

이번에 알게 된 점은 Mounting -> return jsx (렌더링) -> useEffect실행이 된다.

즉, 첫 return 이 끝난 직후 useEffect가 실행된다고 생각하면된다. 그래서 return 문 바로 위에 위치 시켜 놓으면 좋다.

useEffect도 console.log()가 먼저 실행이 되고나서 state변경코드가 실행된다. => 한번에 처리를 하는데 이걸 보고 batching이라고 함

왜 이렇게 순서가 진행되냐면 state변경함수는 비동기 함수이다. 그래서 같은 scope안에서 마지막에 한꺼번에 실행이 된다.
state변경 2개 이상일 경우 한번에 변경이 되고 리렌더링은 한번만 된다.


ComponentDidUpdate🔥

import React, { useEffect, useState } from "react";
import { useQuery } from "react-query";
import { Link } from "react-router-dom";
import { getNowPlaying } from "../api";

export default function Home() {   // 1
  console.log("Home 컴포넌트 최상단 / 렌더링 시작!");  //4 state변경으로 다시 렌더링 시작
  const [string, setString] = useState("초기값");
  const [number, setNumber] = useState(0);
  console.log("string:", string);    //4-1 "변경값"
  console.log("number:", number);    //4-2 100

  useEffect(() => {  //3 return 후 useEffect
    console.log("componentDidMount"); // 컴포넌트 마운트 직후 실행 //3-1
    setString("변경값");  //3-4
    setNumber(100);     //3-5   state처리 한번에 실행
    console.log("비동기 테스트");   //3-2

    return () => {
      console.log("componentWillUnmount"); // 컴포넌트 언마운트 직전 실행   //7
    };
  }, []);

  useEffect(() => {
    console.log("componentDidMount or componentDidUpdate");  //3-3
  }, [string]);    //6 string변경으로 다시 한번더 실행

  return (   //2    //5 
    <div>     
      {console.log("return jsx")}
      <h1>Home</h1>
      <Link to="/company">Go To Company Page</Link>
    </div>
  );
}

순서는 이렇게 진행된다.🤓

 

ReactQuery를 실행한다면?

:useQuery도 render가 한번 일어나고 나서 데이터를 가져오는 함수가 실행된다.

useQuery도 state를 내장하고 있으므로 다시 render가 일어날 것 

const {data ,isLoading} = useQuery("NowPlaying",fetchVideos)
//data : 서버 state

그래서 처음 jsx가 일어날때는 데이터가 없다 그래서 undefined가 일어나고 바로 map을 실행시키면 error가 나온다.

그래서 예외처리 && , 옵셔널체이닝 등이 처리가 필요하다.

 

오늘의 component실행순서 정리 끝😎