Next.js course Β· Module 5: Rendering Strategies

Loading Skeletons and Progress Indicators

18 min read Β·
In this lesson12

In the previous module, we discussed how to use React Suspense and data streaming to improve loading performance and user interface responsiveness. However, simply waiting for data to load without properly informing the user about what's happening can cause frustration and the impression that the application is not working. In this module, we will focus on creating advanced loading skeletons and progress indicators that complement the data streaming strategy and ensure an excellent user experience.

Why Are Loading Skeletons Important?

Loading skeletons and progress indicators are key elements of modern web applications for several reasons:

  1. They reduce perceived latency - even if the actual loading time doesn't change, users perceive it as shorter when they see something is happening
  2. They prevent layout shifts (CLS) - they maintain the page structure, reducing shifts during loading
  3. They communicate application state - they inform the user that data is loading, instead of leaving them uncertain
  4. They improve Core Web Vitals metrics - lower CLS and better LCP (Largest Contentful Paint) translate to better performance scores

Types of Loading State Indicators

There are several approaches to informing the user about the loading state:

  1. Loading skeletons (Skeleton UI) - simplified graphical representations of the content that will be displayed
  2. Progress indicators - visual representations of loading progress (bars, circles)
  3. Indeterminate loaders - animated indicators (e.g., spinning circles) that don't show exact progress
  4. Delayed rendering - showing loading indicators only after a specified time to avoid flickering
  5. Transition animations - smooth transitions between loading states and ready content

Implementing Loading Skeletons in Next.js

1. Basic Skeleton Components

Let's start by creating basic skeleton components that we can use as placeholders during loading:

// components/ui/skeleton.tsx
import { cn } from '@/lib/utils';

interface SkeletonProps extends React.HTMLAttributes<HTMLDivElement> {}

export function Skeleton({ className, ...props }: SkeletonProps) {
  return (
    <div
      className={cn(
        "animate-pulse rounded-md bg-gray-200 dark:bg-gray-800",
        className
      )}
      {...props}
    />
  );
}

This simple component creates a pulsing element that can be customized with classes and properties. We can now use it to create different types of loading skeletons.

2. Advanced Skeletons for Specific Content Types

We can create more advanced skeletons for specific content types, such as product cards, tables, or lists:

// components/skeletons/product-card-skeleton.tsx
import { Skeleton } from "@/components/ui/skeleton";

export function ProductCardSkeleton() {
  return (
    <div className="space-y-4 rounded-lg border p-4">
      {/* Product image skeleton */}
      <Skeleton className="h-[200px] w-full rounded-lg" />

      {/* Product name skeleton */}
      <Skeleton className="h-8 w-3/4" />

      {/* Price and rating skeleton */}
      <div className="flex justify-between">
        <Skeleton className="h-6 w-1/4" />
        <Skeleton className="h-6 w-1/4" />
      </div>

      {/* Button skeleton */}
      <Skeleton className="h-10 w-full" />
    </div>
  );
}
// components/skeletons/table-skeleton.tsx
import { Skeleton } from "@/components/ui/skeleton";

interface TableSkeletonProps {
  rows?: number;
  columns?: number;
}

export function TableSkeleton({ rows = 5, columns = 4 }: TableSkeletonProps) {
  return (
    <div className="w-full space-y-3 rounded-lg border p-4">
      {/* Table header */}
      <div className="flex gap-3 pb-2">
        {Array.from({ length: columns }).map((_, i) => (
          <Skeleton key={`header-${i}`} className="h-10 flex-1" />
        ))}
      </div>

      {/* Table rows */}
      {Array.from({ length: rows }).map((_, rowIndex) => (
        <div key={`row-${rowIndex}`} className="flex gap-3">
          {Array.from({ length: columns }).map((_, colIndex) => (
            <Skeleton
              key={`cell-${rowIndex}-${colIndex}`}
              className="h-12 flex-1"
            />
          ))}
        </div>
      ))}
    </div>
  );
}

3. Using Skeletons with React Suspense

Now we can combine our loading skeletons with React Suspense to use them as fallbacks during data streaming:

// app/products/page.tsx
import { Suspense } from "react";
import { ProductGrid } from "./product-grid";
import { ProductFilters } from "./product-filters";
import { ProductGridSkeleton } from "@/components/skeletons/product-grid-skeleton";
import { ProductFiltersSkeleton } from "@/components/skeletons/product-filters-skeleton";

export default function ProductsPage() {
  return (
    <div className="container mx-auto py-10">
      <h1 className="mb-8 text-3xl font-bold">Our Products</h1>

      <div className="grid grid-cols-4 gap-6">
        <div className="col-span-1">
          <Suspense fallback={<ProductFiltersSkeleton />}>
            <ProductFilters />
          </Suspense>
        </div>

        <div className="col-span-3">
          <Suspense fallback={<ProductGridSkeleton />}>
            <ProductGrid />
          </Suspense>
        </div>
      </div>
    </div>
  );
}

In this example, we create skeletons for the product filters and product grid, so during loading the user sees the appropriate page structure.

Progress Indicators in Next.js

In addition to loading skeletons, we can also use progress indicators to inform the user about the state of operations, especially those that take more time.

1. Simple Progress Indicator

// components/ui/progress.tsx
"use client";

import * as React from "react";
import * as ProgressPrimitive from "@radix-ui/react-progress";
import { cn } from "@/lib/utils";

interface ProgressProps extends React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root> {
  indicatorClassName?: string;
}

const Progress = React.forwardRef<
  React.ElementRef<typeof ProgressPrimitive.Root>,
  ProgressProps
>(({ className, value, indicatorClassName, ...props }, ref) => (
  <ProgressPrimitive.Root
    ref={ref}
    className={cn(
      "relative h-2 w-full overflow-hidden rounded-full bg-gray-100 dark:bg-gray-800",
      className
    )}
    {...props}
  >
    <ProgressPrimitive.Indicator
      className={cn(
        "h-full w-full flex-1 bg-blue-600 transition-all dark:bg-blue-400",
        indicatorClassName
      )}
      style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
    />
  </ProgressPrimitive.Root>
));
Progress.displayName = ProgressPrimitive.Root.displayName;

export { Progress };

2. Indeterminate Loading Indicator (Spinner)

// components/ui/spinner.tsx
import { cn } from "@/lib/utils";

interface SpinnerProps extends React.HTMLAttributes<HTMLDivElement> {
  size?: "sm" | "md" | "lg";
  variant?: "primary" | "secondary";
}

export function Spinner({
  className,
  size = "md",
  variant = "primary",
  ...props
}: SpinnerProps) {
  const sizeClasses = {
    sm: "h-4 w-4 border-2",
    md: "h-6 w-6 border-2",
    lg: "h-10 w-10 border-3",
  };

  const variantClasses = {
    primary: "border-blue-600 border-t-transparent",
    secondary: "border-gray-600 border-t-transparent",
  };

  return (
    <div
      className={cn(
        "inline-block animate-spin rounded-full",
        sizeClasses[size],
        variantClasses[variant],
        className
      )}
      role="status"
      aria-label="loading"
      {...props}
    >
      <span className="sr-only">Loading...</span>
    </div>
  );
}

Application-wide Progress Indicators

In Next.js, we can also implement application-wide progress indicators that inform the user about the navigation state between pages.

1. Global Progress Indicator for Page Transitions

// components/global-progress.tsx
"use client";

import { useEffect, useState } from "react";
import { usePathname, useSearchParams } from "next/navigation";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

export function GlobalProgress() {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [isNavigating, setIsNavigating] = useState(false);

  useEffect(() => {
    // NProgress configuration
    NProgress.configure({ showSpinner: false });

    // Handling navigation start
    function onRouteChangeStart() {
      setIsNavigating(true);
      NProgress.start();
    }

    // Handling navigation end
    function onRouteChangeComplete() {
      setIsNavigating(false);
      NProgress.done();
    }

    // Adding event listeners
    window.addEventListener("beforeunload", onRouteChangeStart);

    // Removing event listeners on component unmount
    return () => {
      window.removeEventListener("beforeunload", onRouteChangeStart);
    };
  }, []);

  // Reacting to path or search parameter changes
  useEffect(() => {
    if (isNavigating) {
      NProgress.done();
      setIsNavigating(false);
    }
  }, [pathname, searchParams, isNavigating]);

  return null; // This component renders nothing, it only manages NProgress
}

Then we can add this component to our layout.tsx:

// app/layout.tsx
import { GlobalProgress } from "@/components/global-progress";

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <GlobalProgress />
        {children}
      </body>
    </html>
  );
}

Advanced Loading State Management Techniques

1. Delayed Loading Indicator Rendering

In some cases, data loading is so fast that showing a loading indicator causes unnecessary interface flickering. We can solve this problem by delaying the loading indicator rendering:

// hooks/use-delayed-loading.tsx
import { useState, useEffect } from "react";

export function useDelayedLoading(loading: boolean, delay = 300) {
  const [showLoading, setShowLoading] = useState(false);

  useEffect(() => {
    if (loading) {
      const timer = setTimeout(() => {
        setShowLoading(true);
      }, delay);

      return () => clearTimeout(timer);
    } else {
      setShowLoading(false);
    }
  }, [loading, delay]);

  return showLoading && loading;
}

Now we can use this hook in our components:

// components/delayed-loading.tsx
"use client";

import { useDelayedLoading } from "@/hooks/use-delayed-loading";

interface DelayedLoadingProps {
  loading: boolean;
  delay?: number;
  fallback: React.ReactNode;
  children: React.ReactNode;
}

export function DelayedLoading({
  loading,
  delay = 300,
  fallback,
  children
}: DelayedLoadingProps) {
  const showLoading = useDelayedLoading(loading, delay);

  return showLoading ? fallback : children;
}

2. Custom Suspense with Delay

We can also create a custom Suspense-based component that introduces a delay:

// components/delayed-suspense.tsx
"use client";

import { Suspense, useState, useEffect } from "react";

interface DelayedSuspenseProps {
  fallback: React.ReactNode;
  children: React.ReactNode;
  delay?: number;
}

export function DelayedSuspense({
  fallback,
  children,
  delay = 300
}: DelayedSuspenseProps) {
  const [showFallback, setShowFallback] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => {
      setShowFallback(true);
    }, delay);

    return () => clearTimeout(timer);
  }, [delay]);

  return (
    <Suspense fallback={showFallback ? fallback : null}>
      {children}
    </Suspense>
  );
}

Managing Cumulative Layout Shift (CLS)

Layout shifts (CLS) are one of the key Core Web Vitals metrics. Well-designed loading skeletons can help minimize layout shifts by maintaining the dimensions and proportions of elements.

1. Preserving Dimensions

// components/skeletons/image-skeleton.tsx
import { Skeleton } from "@/components/ui/skeleton";

interface ImageSkeletonProps {
  width: number;
  height: number;
  aspectRatio?: number;
}

export function ImageSkeleton({ width, height, aspectRatio }: ImageSkeletonProps) {
  return (
    <div
      className="overflow-hidden rounded-lg"
      style={{
        width: width ? `${width}px` : '100%',
        height: height ? `${height}px` : '100%',
        aspectRatio: aspectRatio ? `${aspectRatio}` : undefined,
      }}
    >
      <Skeleton className="h-full w-full" />
    </div>
  );
}

2. Loading Images with Space Preservation

// components/ui/image.tsx
"use client";

import { useState } from "react";
import Image, { ImageProps } from "next/image";
import { Skeleton } from "@/components/ui/skeleton";

interface OptimizedImageProps extends Omit<ImageProps, "onLoad" | "onError"> {
  fallbackClassName?: string;
}

export function OptimizedImage({
  fallbackClassName,
  className,
  alt,
  ...props
}: OptimizedImageProps) {
  const [isLoading, setIsLoading] = useState(true);

  return (
    <div className="relative">
      {isLoading && (
        <Skeleton
          className={fallbackClassName || className}
          style={{
            position: "absolute",
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
          }}
        />
      )}
      <Image
        className={className}
        alt={alt}
        onLoad={() => setIsLoading(false)}
        {...props}
      />
    </div>
  );
}

Form Submission State Indicators

In addition to loading indicators for incoming data, it's also worth showing the state of data submission operations.

1. Button with Loading Indicator

// components/ui/loading-button.tsx
import { ButtonHTMLAttributes } from "react";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { cn } from "@/lib/utils";

interface LoadingButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  loading?: boolean;
  variant?: "default" | "outline" | "ghost" | "link";
  size?: "default" | "sm" | "lg";
  spinnerClassName?: string;
}

export function LoadingButton({
  children,
  loading,
  className,
  spinnerClassName,
  disabled,
  ...props
}: LoadingButtonProps) {
  return (
    <Button
      className={cn("relative", className)}
      disabled={disabled || loading}
      {...props}
    >
      {loading && (
        <span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
          <Spinner size="sm" className={spinnerClassName} />
        </span>
      )}
      <span className={cn(loading ? "invisible" : "")}>{children}</span>
    </Button>
  );
}

2. Form with State Indicator

// components/submit-form.tsx
"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { LoadingButton } from "@/components/ui/loading-button";

export function ContactForm() {
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const router = useRouter();

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setLoading(true);
    setError(null);

    try {
      const formData = new FormData(event.currentTarget);
      const response = await fetch('/api/contact', {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        throw new Error('An error occurred while sending the message');
      }

      setSuccess(true);
      event.currentTarget.reset();

      // Redirect after successful submission
      setTimeout(() => {
        router.push('/contact/thank-you');
      }, 1500);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An unknown error occurred');
    } finally {
      setLoading(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {/* Form fields */}
      <div className="space-y-4">
        <input
          type="text"
          name="name"
          required
          className="w-full rounded-md border p-3"
          disabled={loading}
        />
        <input
          type="email"
          name="email"
          required
          className="w-full rounded-md border p-3"
          disabled={loading}
        />
        <textarea
          name="message"
          required
          className="h-32 w-full rounded-md border p-3"
          disabled={loading}
        />
      </div>

      {/* Form state */}
      {error && (
        <div className="rounded-md bg-red-50 p-4 text-red-600">
          {error}
        </div>
      )}

      {success && (
        <div className="rounded-md bg-green-50 p-4 text-green-600">
          Message sent successfully!
        </div>
      )}

      {/* Submit button */}
      <LoadingButton
        type="submit"
        loading={loading}
        className="w-full"
      >
        Send message
      </LoadingButton>
    </form>
  );
}

Progress Indicators for Long-running Operations

For operations that take longer, it's worth showing progress indicators that inform the user about the current state and remaining time.

1. Percentage Progress Indicator

// components/ui/percent-progress.tsx
"use client";

import { Progress } from "@/components/ui/progress";

interface PercentProgressProps {
  value: number;
  max: number;
  label?: string;
  showPercent?: boolean;
  className?: string;
}

export function PercentProgress({
  value,
  max,
  label,
  showPercent = true,
  className
}: PercentProgressProps) {
  const percent = Math.min(Math.round((value / max) * 100), 100);

  return (
    <div className={className}>
      {label && (
        <div className="mb-2 flex justify-between">
          <span>{label}</span>
          {showPercent && <span>{percent}%</span>}
        </div>
      )}
      <Progress value={percent} />
    </div>
  );
}

2. File Upload Progress Indicator

// components/file-upload-progress.tsx
"use client";

import { useState } from "react";
import { PercentProgress } from "@/components/ui/percent-progress";

interface FileUploadProgressProps {
  onUploadComplete: (url: string) => void;
  accept?: string;
  maxSizeMB?: number;
}

export function FileUploadProgress({
  onUploadComplete,
  accept = "image/*",
  maxSizeMB = 5
}: FileUploadProgressProps) {
  const [progress, setProgress] = useState(0);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];
    if (!file) return;

    // Check file size
    if (file.size > maxSizeMB * 1024 * 1024) {
      setError(`The file is too large. Maximum size is ${maxSizeMB}MB`);
      return;
    }

    setUploading(true);
    setError(null);
    setProgress(0);

    try {
      const formData = new FormData();
      formData.append('file', file);

      const xhr = new XMLHttpRequest();

      // Listening to upload progress
      xhr.upload.addEventListener('progress', (event) => {
        if (event.lengthComputable) {
          const percentComplete = (event.loaded / event.total) * 100;
          setProgress(percentComplete);
        }
      });

      // Handling upload completion
      xhr.addEventListener('load', () => {
        if (xhr.status === 200) {
          const response = JSON.parse(xhr.responseText);
          onUploadComplete(response.url);
        } else {
          setError('An error occurred while uploading the file');
        }
        setUploading(false);
      });

      // Handling errors
      xhr.addEventListener('error', () => {
        setError('A network error occurred while uploading the file');
        setUploading(false);
      });

      // Sending the file
      xhr.open('POST', '/api/upload');
      xhr.send(formData);
    } catch (err) {
      setError('An unexpected error occurred');
      setUploading(false);
    }
  }

  return (
    <div className="space-y-4">
      <label className="block">
        <span className="mb-1 block font-medium">Choose a file:</span>
        <input
          type="file"
          accept={accept}
          onChange={handleUpload}
          disabled={uploading}
          className="w-full cursor-pointer rounded-md border p-2 file:mr-4 file:rounded file:border-0 file:bg-blue-50 file:px-4 file:py-2 file:text-sm file:font-medium file:text-blue-600 hover:file:bg-blue-100"
        />
      </label>

      {uploading && (
        <PercentProgress
          value={progress}
          max={100}
          label="Uploading file"
          showPercent
        />
      )}

      {error && (
        <div className="rounded-md bg-red-50 p-3 text-sm text-red-600">
          {error}
        </div>
      )}
    </div>
  );
}

Integration with React Suspense and Server Components

In Next.js, we can combine our loading skeletons and progress indicators with React Suspense and Server Components to create a smooth user experience.

1. Dynamic Product Page with Different Loading Indicators

// app/products/page.tsx
import { Suspense } from "react";
import { ProductHeader } from "./product-header";
import { ProductGrid } from "./product-grid";
import { ProductFilters } from "./product-filters";
import { ProductSearch } from "./product-search";
import { ProductGridSkeleton } from "@/components/skeletons/product-grid-skeleton";
import { ProductFiltersSkeleton } from "@/components/skeletons/product-filters-skeleton";
import { ProductHeaderSkeleton } from "@/components/skeletons/product-header-skeleton";
import { DelayedSuspense } from "@/components/delayed-suspense";

export default async function ProductsPage({
  searchParams
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
  return (
    <div className="container mx-auto py-10">
      {/* Priority 1: Page header - low latency */}
      <Suspense fallback={<ProductHeaderSkeleton />}>
        <ProductHeader />
      </Suspense>

      {/* Priority 2: Search bar - small delay */}
      <div className="mb-6">
        <ProductSearch initialQuery={(await searchParams).q as string} />
      </div>

      <div className="grid grid-cols-4 gap-6">
        {/* Priority 3: Filters - delayed rendering */}
        <div className="col-span-1">
          <DelayedSuspense
            fallback={<ProductFiltersSkeleton />}
            delay={300}
          >
            <ProductFilters
              initialCategory={(await searchParams).category as string}
              initialPriceRange={{
                min: (await searchParams).minPrice as string,
                max: (await searchParams).maxPrice as string,
              }}
            />
          </DelayedSuspense>
        </div>

        {/* Priority 4: Product grid - with full skeleton */}
        <div className="col-span-3">
          <Suspense fallback={<ProductGridSkeleton items={12} />}>
            <ProductGrid
              category={(await searchParams).category as string}
              query={(await searchParams).q as string}
              sort={(await searchParams).sort as string}
              minPrice={(await searchParams).minPrice as string}
              maxPrice={(await searchParams).maxPrice as string}
            />
          </Suspense>
        </div>
      </div>
    </div>
  );
}

2. Product Component Implementation

// app/products/product-grid.tsx
import { ProductCard } from "@/components/product-card";

interface ProductGridProps {
  category?: string;
  query?: string;
  sort?: string;
  minPrice?: string;
  maxPrice?: string;
}

async function getProducts(params: ProductGridProps) {
  // Parameter conversion
  const minPrice = (await params).minPrice ? parseInt((await params).minPrice) : undefined;
  const maxPrice = (await params).maxPrice ? parseInt((await params).maxPrice) : undefined;

  // Simulating network delay for skeleton loading demonstration
  await new Promise(resolve => setTimeout(resolve, 1500));

  // A real implementation would fetch data from an API or database
  const response = await fetch('https://api.example.com/products', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      category: (await params).category,
      query: (await params).query,
      sort: (await params).sort,
      filters: { price: { min: minPrice, max: maxPrice } }
    }),
    // In a real implementation, you might use cache, revalidate, etc.
    cache: 'no-store'
  });

  if (!response.ok) {
    throw new Error('Problem fetching products');
  }

  return response.json();
}

export async function ProductGrid(props: ProductGridProps) {
  const products = await getProducts(props);

  if (products.length === 0) {
    return (
      <div className="py-10 text-center">
        <h3 className="text-xl font-medium">No products found</h3>
        <p className="mt-2 text-gray-500">
          Try changing your search criteria or filters
        </p>
      </div>
    );
  }

  return (
    <div className="grid grid-cols-3 gap-6">
      {products.map(product => (
        <ProductCard key={product.id} product={product} />
      ))}
    </div>
  );
}

Loading State Indicators in Client Components

In client components, we use different methods to display loading state indicators because we cannot use React Suspense for asynchronous data fetching in these components.

1. useAsyncData Hook for Loading Indicators

// hooks/use-async-data.ts
import { useState, useEffect } from "react";

type AsyncStatus = "idle" | "loading" | "success" | "error";

interface UseAsyncDataResult<T> {
  data: T | null;
  status: AsyncStatus;
  error: Error | null;
  isLoading: boolean;
  isSuccess: boolean;
  isError: boolean;
  reload: () => void;
}

export function useAsyncData<T>(
  fetchFn: () => Promise<T>,
  dependencies: any[] = []
): UseAsyncDataResult<T> {
  const [data, setData] = useState<T | null>(null);
  const [status, setStatus] = useState<AsyncStatus>("idle");
  const [error, setError] = useState<Error | null>(null);
  const [reloadCounter, setReloadCounter] = useState(0);

  function reload() {
    setReloadCounter(prev => prev + 1);
  }

  useEffect(() => {
    let isMounted = true;

    async function loadData() {
      setStatus("loading");
      setError(null);

      try {
        const result = await fetchFn();

        if (isMounted) {
          setData(result);
          setStatus("success");
        }
      } catch (e) {
        if (isMounted) {
          setError(e instanceof Error ? e : new Error(String(e)));
          setStatus("error");
        }
      }
    }

    loadData();

    return () => {
      isMounted = false;
    };
  }, [...dependencies, reloadCounter]);

  return {
    data,
    status,
    error,
    isLoading: status === "loading",
    isSuccess: status === "success",
    isError: status === "error",
    reload,
  };
}

2. Using the Hook in a Client Component

// components/user-dashboard.tsx
"use client";

import { useAsyncData } from "@/hooks/use-async-data";
import { Spinner } from "@/components/ui/spinner";
import { ProductCardSkeleton } from "@/components/skeletons/product-card-skeleton";

interface UserDashboardProps {
  userId: string;
}

async function fetchUserDashboardData(userId: string) {
  const response = await fetch(`/api/users/${userId}/dashboard`);
  if (!response.ok) {
    throw new Error('Problem fetching dashboard data');
  }
  return response.json();
}

export function UserDashboard({ userId }: UserDashboardProps) {
  const {
    data,
    isLoading,
    isError,
    error,
    reload
  } = useAsyncData(() => fetchUserDashboardData(userId), [userId]);

  if (isLoading) {
    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <h2 className="text-2xl font-bold">Your Dashboard</h2>
          <div>
            <Spinner size="md" />
          </div>
        </div>

        <div className="grid grid-cols-3 gap-4">
          {Array.from({ length: 6 }).map((_, i) => (
            <ProductCardSkeleton key={i} />
          ))}
        </div>
      </div>
    );
  }

  if (isError) {
    return (
      <div className="rounded-lg bg-red-50 p-6 text-center">
        <h3 className="text-lg font-medium text-red-800">An error occurred</h3>
        <p className="mt-2 text-red-600">{error?.message}</p>
        <button
          onClick={reload}
          className="mt-4 rounded-md bg-red-100 px-4 py-2 text-red-800 hover:bg-red-200"
        >
          Try again
        </button>
      </div>
    );
  }

  if (!data) {
    return null;
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-2xl font-bold">Welcome, {data.user.name}</h2>
        <button
          onClick={reload}
          className="rounded-md bg-gray-100 p-2 hover:bg-gray-200"
          aria-label="Refresh data"
        >
          <RefreshIcon className="h-5 w-5" />
        </button>
      </div>

      <div className="grid grid-cols-3 gap-4">
        {data.recentlyViewed.map(product => (
          <ProductCard key={product.id} product={product} />
        ))}
      </div>

      {/* Other dashboard sections */}
    </div>
  );
}

// Icon component
function RefreshIcon({ className }: { className?: string }) {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      className={className}
    >
      <path d="M21 2v6h-6" />
      <path d="M3 12a9 9 0 0 1 15-6.7L21 8" />
      <path d="M3 22v-6h6" />
      <path d="M21 12a9 9 0 0 1-15 6.7L3 16" />
    </svg>
  );
}

Summary and Best Practices

Here are the key principles for creating effective loading skeletons and progress indicators in Next.js:

  1. Match the content - loading skeletons should reflect the shape and proportions of the actual content

  2. Display strategies:

    • For fast operations (< 300ms) - consider no indicator to avoid flickering
    • For medium operations (300ms - 1s) - use skeletons or spinners
    • For long operations (> 1s) - use progress indicators with actual progress (if possible)
  3. Content prioritization - show critical UI elements first:

    • Header and navigation
    • Main page content
    • Auxiliary elements (filters, side panels) last
  4. Minimize CLS - always define dimensions and proportions for loading skeletons

  5. Accessibility - remember the accessibility of loading indicators:

    • Use appropriate ARIA attributes (aria-busy, aria-label)
    • Provide text alternatives for visual indicators
    • Avoid flashing animations that can be problematic for people with epilepsy
  6. Optimization for mobile devices - adapt loading indicators to different screen sizes and use appropriate skeletons for mobile layouts

  7. Visual consistency - maintain a consistent look for loading skeletons with the rest of the user interface (colors, rounded corners, spacing)

In times when users expect an instant response, well-designed loading states are a key element of user experience. With the techniques described in this module, you can create applications that seem to work faster and provide a smoother experience, even when data is loading in the background.

In the next module, we will discuss partial prerendering, which is the next step in optimizing the performance of Next.js applications and allows for an even better user experience.

Code for this lesson: App.tsx
import React, { useState, useEffect } from 'react';

// Skeleton components and loading states in Next.js

function SkeletonLine({ width = '100%' }: { width?: string }) {
  return (
    <div style={{
      height: 14, background: 'linear-gradient(90deg, #1a2744 25%, #243b5e 50%, #1a2744 75%)',
      backgroundSize: '200% 100%', borderRadius: 4, width,
      animation: 'shimmer 1.5s ease-in-out infinite',
    }} />
  );
}

function SkeletonCard() {
  return (
    <div style={{ background: '#0d1117', borderRadius: 8, padding: 16, border: '1px solid #333' }}>
      <div style={{ height: 120, background: '#1a2744', borderRadius: 6, marginBottom: 12 }} />
      <SkeletonLine width="70%" />
      <div style={{ height: 8 }} />
      <SkeletonLine width="90%" />
      <div style={{ height: 8 }} />
      <SkeletonLine width="50%" />
    </div>
  );
}

// Real product card
function ProductCard({ name, price, desc }: { name: string; price: string; desc: string }) {
  return (
    <div style={{ background: '#1a2744', borderRadius: 8, padding: 16, border: '1px solid #64ffda' }}>
      <div style={{
        height: 120, background: 'linear-gradient(135deg, #0d47a1, #1a237e)',
        borderRadius: 6, marginBottom: 12, display: 'flex', alignItems: 'center',
        justifyContent: 'center', fontSize: 32
      }}>
        {name === 'Quantum Shield' ? 'β—†' : name === 'Neural Link' ? 'β—†' : 'β†―'}
      </div>
      <h3 style={{ color: '#64ffda', margin: 0 }}>{name}</h3>
      <p style={{ color: '#aaa', margin: '8px 0', fontSize: 13 }}>{desc}</p>
      <div style={{ color: '#4caf50', fontWeight: 'bold' }}>{price}</div>
    </div>
  );
}

const products = [
  { name: 'Quantum Shield', price: '2500 QC', desc: 'Next-generation quantum protection' },
  { name: 'Neural Link', price: '4200 QC', desc: 'Direct connection to the network' },
  { name: 'Flux Capacitor', price: '8800 QC', desc: 'Time travel - beta version' },
];

export default function SkeletonDemo() {
  const [loaded, setLoaded] = useState(false);
  const [loading, setLoading] = useState(false);

  const simulateLoad = () => {
    setLoaded(false);
    setLoading(true);
    setTimeout(() => { setLoading(false); setLoaded(true); }, 2500);
  };

  useEffect(() => { simulateLoad(); }, []);

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#e0e0e0', fontFamily: 'monospace' }}>
      <style>{`@keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }`}</style>
      <h1 style={{ color: '#64ffda' }}>Skeleton Loading States</h1>
      <p style={{ color: '#888' }}>Skeleton components improve perceived loading speed</p>
      <button onClick={simulateLoad} style={{
        background: '#2196f3', color: '#fff', border: 'none', borderRadius: 6,
        padding: '8px 16px', cursor: 'pointer', margin: '12px 0', fontFamily: 'monospace'
      }}>
        Reload data
      </button>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 16 }}>
        {loading
          ? [0, 1, 2].map(i => <SkeletonCard key={i} />)
          : loaded
            ? products.map(p => <ProductCard key={p.name} {...p} />)
            : null}
      </div>
    </div>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Client Components in App Router are marked by:

  2. 2. Revalidation in Next.js is used for:

Hands-on tasks in the game

  • Code editor

    Create a Client Component with useState and event handlers for an interactive interface

  • Vertical ordering

    Arrange the elements in correct order: <Suspense -> fallback={<Loading />}> -> <AsyncComponent /> -> </Suspense>

  • Click in order

    Arrange the Suspense component import syntax from React

  • Code editor

    Create a product page with ISR - data revalidation every 3600 seconds

  1. QuestionClient Components in App Router are marked by:
  2. QuestionRevalidation in Next.js is used for:
  3. Coding taskPractice: Create a Client Component with useState and event handlers
  4. Put in orderOrder: <Suspense -> fallback={<Loading />}> -> ...
  5. Click in orderOrder: import -> { -> Suspense
  6. Coding taskPractice: Create a product page with ISR - data revalidation every 3600 seconds

Useful articles