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:
app/
βββ dashboard/
βββ loading.tsx
βββ page.tsxapp/dashboard/loading.tsx:
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:
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
Dashboardheading and theUserProfilecomponent will be displayed immediately. - The "Loading recent sales..." fallback UI will be shown in place of the
RecentSalescomponent. - Once the
RecentSalescomponent 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:
app/
βββ dashboard/
βββ error.tsx
βββ page.tsxapp/dashboard/error.tsx:
'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:
app/
βββ not-found.tsx
βββ page.tsxapp/not-found.tsx:
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:
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
- Official Next.js Documentation on Loading UI and Streaming: https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming
- Official Next.js Documentation on Error Handling: https://nextjs.org/docs/app/building-your-application/routing/error-handling
- Official Next.js Documentation on Not Found UI: https://nextjs.org/docs/app/building-your-application/routing/not-found
- React Documentation on
<Suspense>: https://react.dev/reference/react/Suspense
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:
Root Loading State: Implement the
DashboardLoadingcomponent. This component should serve as the main loading UI for the entire page, simulating the behavior of aloading.tsxfile.Granular Suspense Boundaries: The
UserPostsandUserActivitycomponents fetch data with different delays. Wrap each of them in a React<Suspense>boundary within theDashboardPagecomponent. Provide a unique skeleton loader for each as afallback.- For
UserPosts, use thePostsSkeletoncomponent as the fallback. - For
UserActivity, use theActivitySkeletoncomponent as the fallback.
- For
Error Handling: The
fetchUserPostsfunction is designed to fail. Implement theDashboardErrorcomponent to act as an error boundary, simulatingerror.tsx. It must accepterrorandresetprops. Wrap the<Suspense>boundary forUserPostswith a conceptual error boundary that uses yourDashboardErrorcomponent.Not Found State: If the
fetchUserInfofunction returnsnull(simulating a non-existent user), theDashboardPageshould render theUserNotFoundcomponent. This mimics the behavior of callingnotFound()and rendering anot-found.tsxfile.
Expected result
Your final code should correctly assemble the components to meet all requirements. When the DashboardPage component is rendered:
- If
userIdis'invalid-user', it should display only theUserNotFoundcomponent. - For a valid
userId, it should initially show theDashboardLoadingcomponent. - After the initial user info loads, it should display the user's name.
- Simultaneously, it should display the
PostsSkeletonandActivitySkeletonfallbacks while their respective data is being fetched. - Because
fetchUserPostsfails, thePostsSkeletonshould be replaced by theDashboardErrorcomponent, which displays an error message and a 'Try again' button. - After 3 seconds, the
ActivitySkeletonshould be replaced by the actual user activity list. - The rest of the page layout (e.g., the
<h1>and user info) should remain visible and interactive even when the posts component fails.