0Pricing
Next.js 15 Fullstack Web Apps · Урок

Соглашения для интерфейсов загрузки и ошибок

Используйте соглашения App Router для файлов loading.js, error.js и not-found.js, чтобы создавать надёжные маршруты с потоковой передачей и корректными резервными вариантами.

«Соглашения для интерфейсов загрузки и ошибок» — бесплатный урок Next.js 15 Fullstack Web Apps на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Next.js 15 Fullstack Web Apps, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Next.js 15 Fullstack Web Apps содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Why Loading and Error UI Matter

Advanced routing is not only about where a route lives but about what users see while it resolves or fails. The App Router gives you special files that wrap segments automatically.

  • loading.js renders an instant fallback while the segment streams.
  • error.js catches runtime errors in that segment.
  • not-found.js renders when notFound() is called.

The loading.js Convention

A loading.js file in a segment folder is automatically wrapped around page.js in a React Suspense boundary. While the server component awaits data, the loading UI shows instantly.

export default function Loading() {
  return <div className="spinner">Loading dashboard...</div>;
}

Skeletons Beat Spinners

For perceived performance, render a skeleton that mirrors the final layout instead of a generic spinner. It reduces layout shift and feels faster.

export default function Loading() {
  return (
    <ul>
      {Array.from({ length: 5 }).map((_, i) => (
        <li key={i} className="skeleton-row" />
      ))}
    </ul>
  );
}

Streaming with Suspense

Because loading.js is just Suspense under the hood, the rest of the layout renders immediately while only the slow segment streams in. You can also nest your own Suspense boundaries inside a page for finer control.

import { Suspense } from 'react';

export default function Page() {
  return (
    <section>
      <h1>Reports</h1>
      <Suspense fallback={<p>Loading chart...</p>}>
        <SlowChart />
      </Suspense>
    </section>
  );
}

The error.js Convention

error.js must be a Client Component. It receives the thrown error and a reset function to retry rendering the segment.

'use client';

export default function Error({ error, reset }) {
  return (
    <div>
      <p>Something went wrong: {error.message}</p>
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}

Error Boundaries Are Scoped

An error.js catches errors in its segment and its children, but not in the layout at the same level. To catch layout errors, place the error file one level up.

  • Errors bubble up to the nearest parent boundary.
  • The root layout cannot be caught by a sibling error file.

global-error.js for the Root

To catch errors in the root layout itself, add global-error.js. It replaces the entire document, so it must render its own <html> and <body> tags.

'use client';

export default function GlobalError({ error, reset }) {
  return (
    <html>
      <body>
        <h2>App crashed</h2>
        <button onClick={() => reset()}>Reload</button>
      </body>
    </html>
  );
}

Triggering not-found.js

Call notFound() from next/navigation inside a server component to render the nearest not-found.js and send a 404 status.

import { notFound } from 'next/navigation';

export default async function Page({ params }) {
  const post = await getPost(params.id);
  if (!post) notFound();
  return <article>{post.title}</article>;
}

Custom not-found.js UI

Place not-found.js in any segment to override the default 404 for that part of the route tree. A root-level one acts as the global 404 page.

import Link from 'next/link';

export default function NotFound() {
  return (
    <div>
      <h2>Post not found</h2>
      <Link href="/blog">Back to blog</Link>
    </div>
  );
}

Combining the Conventions

A robust segment folder often contains all four files working together:

  • page.js — the content
  • loading.js — streamed fallback
  • error.js — runtime failure recovery
  • not-found.js — missing resource

Each is wired up automatically by the App Router with no manual provider setup.

Logging Errors in Production

Use a useEffect inside error.js to report errors to your monitoring service while still showing recovery UI to the user.

'use client';
import { useEffect } from 'react';

export default function Error({ error, reset }) {
  useEffect(() => {
    reportToSentry(error);
  }, [error]);
  return <button onClick={reset}>Retry</button>;
}

Quick Check

Which statement about error.js in the App Router is correct?

Recap

You learned the App Router's resilience conventions:

  • loading.js wraps segments in Suspense for instant streamed fallbacks.
  • error.js (Client Component) recovers from runtime errors with reset.
  • global-error.js catches root-layout failures.
  • not-found.js renders when notFound() is called.

Together they make advanced routes graceful under load and failure.

Часто задаваемые вопросы

Урок «Соглашения для интерфейсов загрузки и ошибок» бесплатный?

Да — полный текст урока «Соглашения для интерфейсов загрузки и ошибок» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Next.js 15 Fullstack Web Apps, подпишись на CoddyKit PRO. Курс Next.js 15 Fullstack Web Apps содержит 4 уроков всего.

Чему я научусь в уроке «Соглашения для интерфейсов загрузки и ошибок»?

Используйте соглашения App Router для файлов loading.js, error.js и not-found.js, чтобы создавать надёжные маршруты с потоковой передачей и корректными резервными вариантами. Ты практикуешь Next.js 15 Fullstack Web Apps с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Next.js 15 Fullstack Web Apps?

Предыдущий опыт не требуется. Next.js 15 Fullstack Web Apps на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Соглашения для интерфейсов загрузки и ошибок»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Next.js 15 Fullstack Web Apps?

Да. Каждый урок Next.js 15 Fullstack Web Apps включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Динамические маршруты и сегменты catch-all
  2. Вложенные макеты и группы маршрутов
  3. Параллельные и перехватывающие маршруты
  4. Соглашения для интерфейсов загрузки и ошибок
← Назад к Next.js 15 Fullstack Web Apps