Learn Next.js Β· 11/15

UX Patterns: Loading and Error Handling

7 min read

πŸš† UX Patterns: Loading and Error Handling in Next.js

Welcome, fellow traveler on the web development express! πŸ›€οΈ Today, we're diving into some crucial user experience (UX) patterns in Next.js. A great app isn't just about what it does, but also about how it feels to use it. A big part of that feeling comes from how the app behaves when things are loading or when, inevitably, something goes wrong.

The Problem: Imagine you click a link and... nothing. Just a blank white screen staring back at you for a few seconds. It's like knocking on a door and getting no answer – you start to wonder if anyone's even home. Similarly, if something breaks and the user sees a cryptic error message, or worse, a crashed application, it's a surefire way to send them packing.

The Solution: Next.js provides a set of elegant, file-based conventions to handle these exact scenarios, making your application feel fast, responsive, and robust. We'll explore how to show users that you're on it (with loading states) and how to apologize gracefully when things go sideways (with error handling).


πŸ’¨ 1. Instant Loading States with loading.tsx

Let's start with the "is anyone home?" problem. When a user navigates to a new page, especially one that needs to fetch some data, there's a delay. An instant loading state is a placeholder UI, like a spinner or a skeleton of the page, that shows up immediately. This assures users that the app is working and their content is on its way.

Next.js makes creating these loading states incredibly simple with a special file: loading.tsx (or loading.js).

How it Works:

When you create a loading.tsx file in a folder within the app directory, Next.js will automatically wrap the page.tsx in that same folder with a React <Suspense> boundary. This means that while the content of your page is being prepared on the server, your loading UI will be shown instantly.

Let's imagine you're building a dashboard. You can create a loading state for it like so:

File Structure:

nix
app/
└── dashboard/
    β”œβ”€β”€ loading.tsx
    └── page.tsx

app/dashboard/loading.tsx:

typescript
export default function Loading() {
  // You can add any UI inside Loading, including a Skeleton.
  return <div>Loading your awesome dashboard... Spinner πŸŒ€</div>;
}

Now, when a user navigates to /dashboard, they will immediately see the "Loading your awesome dashboard... Spinner πŸŒ€" message while the actual dashboard page is being rendered on the server. Once the page is ready, it will automatically be swapped in.

Fun Fact: Under the hood, Next.js is cleverly streaming the HTML to the browser. It sends the static parts of your layout and your loading UI first, and then streams the rest of the content as it becomes available. This makes your application feel incredibly fast.


🌊 2. Streaming UI with React <Suspense> Boundaries

The loading.tsx file is fantastic for page-level loading states. But what if a page has multiple sections that load data independently? You wouldn't want a slow-loading chart to block the rendering of the entire page. This is where you can get more granular with React's built-in <Suspense> component.

The Problem: A single slow component can bottleneck the entire page load. Users have to wait for everything to be ready before they see anything.

The Solution: By wrapping slower components in <Suspense> boundaries, you can stream them to the user as they become ready.

Let's enhance our dashboard. Imagine it has a user profile section and a list of recent sales, and the sales data takes a bit longer to fetch.

app/dashboard/page.tsx:

typescript
import { Suspense } from 'react';
import UserProfile from './UserProfile';
import RecentSales from './RecentSales';

export default function DashboardPage() {
  return (
    <div>
      <h1>Dashboard</h1>
      <UserProfile />
      <Suspense fallback={<p>Loading recent sales...</p>}>
        <RecentSales />
      </Suspense>
    </div>
  );
}

In this example:

  • The Dashboard heading and the UserProfile component will be displayed immediately.
  • The "Loading recent sales..." fallback UI will be shown in place of the RecentSales component.
  • Once the RecentSales component has fetched its data and is ready to render, it will replace the fallback UI.

This approach provides a much better user experience because users can start interacting with parts of the page while other parts are still loading.

Real-world Scenario: Think of a news website. The main article content might load instantly, while the comments section and related articles, which require separate data fetches, can be streamed in later using <Suspense>.


gracefully 3. Graceful Failure: Creating error.tsx Error Boundaries

Even the best-laid plans can go awry. An API might be down, or some unexpected data might cause a component to crash. Without proper error handling, this could bring down your entire application.

The Problem: An unhandled error in a component can crash the entire page, leaving the user with a broken experience.

The Solution: Next.js provides a special error.tsx file that acts as a catch-all for unexpected errors within a route segment. It allows you to display a fallback UI and even provides a way for users to try and recover from the error.

How it Works:

Similar to loading.tsx, you create an error.tsx file within a route's folder. This file must be a Client Component (using the "use client" directive). It receives two props: error (the error object) and reset (a function to re-render the boundary's content).

File Structure:

nix
app/
└── dashboard/
    β”œβ”€β”€ error.tsx
    └── page.tsx

app/dashboard/error.tsx:

typescript
'use client'; // Error components must be Client Components

import { useEffect } from 'react';

export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    // Log the error to an error reporting service
    console.error(error);
  }, [error]);

  return (
    <div>
      <h2>Something went wrong! 😱</h2>
      <button
        onClick={
          // Attempt to recover by trying to re-render the segment
          () => reset()
        }
      >
        Try again
      </button>
    </div>
  );
}

Now, if any error occurs while rendering the dashboard page or any of its children, this error boundary will be displayed instead. The rest of your application, like the main layout and navigation, will remain functional. This is a huge win for user experience and application stability.


❓ 4. Handling Missing Resources: Custom 404 Pages with not-found.tsx

Sometimes, a user might try to access a page that doesn't exist. By default, Next.js shows a generic 404 Not Found page. While functional, it's a bit bland. You can create a much more user-friendly and on-brand experience by creating a custom 404 page.

The Problem: A user follows a broken link or mistypes a URL and is met with a generic, unhelpful "Not Found" page.

The Solution: Next.js allows you to create a custom 404 page by adding a not-found.tsx file to your app directory.

How it Works:

You can create a global 404 page or more specific ones for different sections of your application. To create a global 404 page, simply add not-found.tsx to the root of your app directory.

File Structure:

css
app/
β”œβ”€β”€ not-found.tsx
└── page.tsx

app/not-found.tsx:

typescript
import Link from 'next/link';

export default function NotFound() {
  return (
    <div>
      <h2>Page Not Found</h2>
      <p>Could not find the requested resource. Maybe you're looking for a unicorn? πŸ¦„</p>
      <Link href="/">Return Home</Link>
    </div>
  );
}

You can also trigger a 404 page programmatically using the notFound() function from next/navigation. This is useful, for example, if a user tries to access a product with an ID that doesn't exist in your database.

app/products/[id]/page.tsx:

typescript
import { notFound } from 'next/navigation';

async function getProduct(id: string) {
  const res = await fetch(`https://api.example.com/products/${id}`);
  if (!res.ok) {
    return undefined;
  }
  return res.json();
}

export default async function ProductPage({ params }: { params: { id: string } }) {
  const product = await getProduct(params.id);

  if (!product) {
    notFound();
  }

  return <div>{product.name}</div>;
}

If getProduct returns undefined, the notFound() function will be called, and the nearest not-found.tsx file in the directory structure will be rendered.

Interesting Tidbit: You can have nested not-found.tsx files. For instance, a not-found.tsx inside /app/dashboard would only apply to routes within the dashboard, allowing for more specific "not found" messages.


πŸ“š Further Reading and Resources

Challenge

Challenge: Implement Robust Page UI with Loading, Error, and Not Found States

You are tasked with building a user dashboard page that fetches and displays several pieces of data. Your goal is to implement a robust user experience using Next.js conventions for loading, error, and not-found states, all within a single file for this exercise.

Requirements:

  1. Root Loading State: Implement the DashboardLoading component. This component should serve as the main loading UI for the entire page, simulating the behavior of a loading.tsx file.

  2. Granular Suspense Boundaries: The UserPosts and UserActivity components fetch data with different delays. Wrap each of them in a React <Suspense> boundary within the DashboardPage component. Provide a unique skeleton loader for each as a fallback.

    • For UserPosts, use the PostsSkeleton component as the fallback.
    • For UserActivity, use the ActivitySkeleton component as the fallback.
  3. Error Handling: The fetchUserPosts function is designed to fail. Implement the DashboardError component to act as an error boundary, simulating error.tsx. It must accept error and reset props. Wrap the <Suspense> boundary for UserPosts with a conceptual error boundary that uses your DashboardError component.

  4. Not Found State: If the fetchUserInfo function returns null (simulating a non-existent user), the DashboardPage should render the UserNotFound component. This mimics the behavior of calling notFound() and rendering a not-found.tsx file.

Expected result

Your final code should correctly assemble the components to meet all requirements. When the DashboardPage component is rendered:

  1. If userId is 'invalid-user', it should display only the UserNotFound component.
  2. For a valid userId, it should initially show the DashboardLoading component.
  3. After the initial user info loads, it should display the user's name.
  4. Simultaneously, it should display the PostsSkeleton and ActivitySkeleton fallbacks while their respective data is being fetched.
  5. Because fetchUserPosts fails, the PostsSkeleton should be replaced by the DashboardError component, which displays an error message and a 'Try again' button.
  6. After 3 seconds, the ActivitySkeleton should be replaced by the actual user activity list.
  7. The rest of the page layout (e.g., the <h1> and user info) should remain visible and interactive even when the posts component fails.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.