Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Handling Loading and Error States | Section
Building Web Apps with Next.js

bookHandling Loading and Error States

Swipe um das Menü anzuzeigen

When working with data, there are two important situations you need to handle:

  • The data is still loading;
  • Something goes wrong while loading the data.

Next.js provides built-in support for both cases using special files: loading.tsx and error.tsx.

These files allow you to define what the user sees while data is loading or when an error occurs.

Loading State with loading.tsx

You can create a loading.tsx file inside a route folder:

app/
  products/
    loading.tsx
    page.tsx

Example:

export default function Loading() {
  return <p>Loading...</p>;
}

This component is automatically shown while the page is waiting for data.

Error State with error.tsx

To handle errors, create an error.tsx file:

app/
  products/
    error.tsx
    page.tsx

Example:

"use client";

export default function Error({ error }) {
  return <p>Something went wrong.</p>;
}

This component is displayed if an error happens during rendering or data fetching.

How It Works

Next.js automatically detects these files and uses them when needed. You do not need to manually manage loading or error states for each request.

When data is being fetched, the loading component is shown. If an error occurs, the error component is displayed instead of the page.

Why This Is Useful

Handling these states improves user experience.

Instead of showing a blank page or crashing, your app provides feedback and remains stable.

It also keeps your components cleaner, because you do not need to write loading and error logic manually in every component.

question mark

Which file is used to show a loading state in Next.js App Router?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 25

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 1. Kapitel 25
some-alt