언어·프레임워크/Next.js

[Next.js] 인프런 강의 "Next.js 필수 개발 가이드 3시간 완성!" 정리(Loading UI)

DandyNow 2024. 2. 11. 14:34
728x90
반응형

📌 Loading UI

1. React Suspense

// src/app/layout.tsx

// (생략)
import { Suspense } from "react"; // 추가

// (생략)

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en" data-theme="dark">
      <body className={inter.className}>
        <NavBar />
        <main>
          {/* Suspense 컴포넌트 적용 */}
          {/* fallback에는 텍스트, 아이콘, 애니메이션 컴포넌트 적용 가능 */}
          {/* 검색 엔진 봇이 보는 페이지는 빈 페이지가 아닌 로딩 컴포넌트가 렌더링 된 문서 */}
          {/* server는 사용자 페이지가 렌더링 될 때까지 대기한 후 추가 데이터를 client에 전달 → 스트리밍 */}
          <Suspense fallback={<p>Loading...</p>}>{children}</Suspense>
        </main>
      </body>
    </html>
  );
}

 

[그림 1] React Developer Tools에서 suspense를 확인 가능, true로 설정한 화면

 

2. loading.tsx

  • loading.tsx 컴포넌트를 작성하면 React Suspense 컴포넌트를 사용하지 않아도 된다. 
// src/app/loading.tsx

import React from "react";

const Loading = () => {
  return <div>Loading...</div>;
};

export default Loading;
// src/app/layout.tsx

// (생략)
import { Suspense } from "react"; // 추가

// (생략)

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en" data-theme="dark">
      <body className={inter.className}>
        <NavBar />
        <main>
          {/* React Suspense 컴포넌트를 사용 안해도 된다. */}
          {/* <Suspense fallback={<p>Loading...</p>}>{children}</Suspense> */}
          {children}
        </main>
      </body>
    </html>
  );
}

 

3. 로딩 애니메이션(daisyUI)

// src/app/loading.tsx

import React from "react";

const Loading = () => {
  // https://daisyui.com/components/loading/
  return <span className="loading loading-spinner text-primary"></span>;
};

export default Loading;

 

728x90
반응형