[Next JS] 모든 페이지 내에서 로딩 화면 설정하기

루비·2023년 6월 10일
0

NextJS

목록 보기
5/7
import "@/styles/globals.scss";
import type { AppProps } from "next/app";
import Layout from "@/components/layout/Layout";
import { SessionProvider, useSession } from "next-auth/react";
import React, { useEffect, useState } from "react";
import router from "next/router";
import Loading from "@/components/loading/Loading";

export default function App({ Component, pageProps }: AppProps) {
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const startLoading = () => setLoading(true);
    const stopLoading = () => setLoading(false);

    // Register event listeners to show/hide the loading component
    // addEventListener : documen의 특정 요소 (id, class, tag ... ) event(클릭하면 함수를 실행하라.)
    window.addEventListener("beforeunload", startLoading);
    router.events.on("routeChangeStart", startLoading);
    router.events.on("routeChangeComplete", stopLoading);
    router.events.on("routeChangeError", stopLoading);

    // Unregister event listeners during cleanup
    // window.removeEventListener 이벤트 제거할 경우
    return () => {
      window.removeEventListener("beforeunload", startLoading);
      router.events.off("routeChangeStart", startLoading);
      router.events.off("routeChangeComplete", stopLoading);
      router.events.off("routeChangeError", stopLoading);
    };
  }, []);

  return (
    <SessionProvider session={pageProps.session}>
      {loading ? (
        <Loading />
      ) : (
        <Layout>
          <Component {...pageProps} />
        </Layout>
      )}
    </SessionProvider>
  );
}
profile
개발훠훠

0개의 댓글