0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · Lección

UI de carga y errores

Implemente estados de carga con `loading.js` y gestione los errores correctamente mediante los boundaries `error.js` de su aplicación.

UI de carga y errores es una lección gratuita de Next.js 15 Fullstack (App Router + Server Actions) en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Next.js 15 Fullstack (App Router + Server Actions), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Next.js 15 Fullstack (App Router + Server Actions) incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Why Loading States Matter

When your Next.js application fetches data, it can take some time. Without any visual feedback, users might think the app is frozen or broken.

  • Improve User Experience: Keep users informed.
  • Reduce Frustration: Prevent perceived slowness.
  • Indicate Progress: Show that something is happening in the background.

Introducing `loading.js`

Next.js App Router provides a special file convention, loading.js, to automatically create a loading UI for a route segment.

When data is being fetched for a page.js or layout.js file, Next.js automatically displays the UI defined in its nearest loading.js sibling or ancestor.

Creating a Simple Loading UI

To create a loading UI, simply add a loading.js file inside a route segment folder. It should export a default React component.

This component will be rendered instantly when the segment is loading.

export default function Loading() {
  return (
    <div style={{ padding: '20px', textAlign: 'center' }}>
      <h2>Loading...</h2>
      <p>Please wait while we fetch the content.</p>
    </div>
  );
}

How `loading.js` Works

Under the hood, loading.js works with React Suspense. Next.js wraps the corresponding page.js and its nested children in a Suspense Boundary.

When any data fetching inside that boundary is pending, the loading.js component is shown as a fallback.

Nested Loading States

You can have multiple loading.js files at different levels of your route. For example, a global loading UI and a more specific one for a sub-route.

Next.js will show the closest ancestor loading.js for the segment that is currently loading.

Handling Application Errors

Just like loading states, errors are a part of any application. Uncaught errors can crash your app, leading to a poor user experience.

Next.js App Router provides a way to gracefully handle errors and display a custom error UI using error.js.

Introducing `error.js`

The error.js file convention allows you to define an error UI that automatically wraps a route segment and its children in a React Error Boundary.

This boundary catches errors that occur during rendering, in event handlers, and in data fetching within its scope.

Creating a Basic Error UI

Similar to loading.js, create an error.js file in a route segment. It must be a React Client Component (use 'use client'; at the top).

It receives error (the error object) and a reset function as props.

'use client';

import { useEffect } from 'react';

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

  return (
    <div style={{ padding: '20px', textAlign: 'center', color: 'red' }}>
      <h2>Something went wrong!</h2>
      <button
        onClick={() => reset()} // Attempt to re-render the segment
        style={{ marginTop: '10px', padding: '8px 15px' }}
      >
        Try again
      </button>
    </div>
  );
}

Error Recovery with `reset()`

The reset() function provided to your error.js component is crucial. When called, it attempts to re-render the entire segment that threw the error.

This allows users to try again without navigating away, potentially resolving transient issues.

Quick Check on UI Files

Which statement accurately describes the primary purpose of loading.js in Next.js App Router?

Recap: Loading & Error UI

In this lesson, you learned how to enhance your Next.js application's user experience by implementing visual feedback for loading and error states.

  • loading.js: Displays a temporary UI while data is being fetched, using React Suspense.
  • error.js: Catches errors in a segment and displays a fallback UI, allowing users to attempt recovery with the reset() function.

These conventions help create more robust and user-friendly Next.js applications.

Preguntas frecuentes

¿La lección «UI de carga y errores» es gratis?

Sí — el texto completo de «UI de carga y errores» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Next.js 15 Fullstack (App Router + Server Actions), actualiza a CoddyKit PRO. El curso de Next.js 15 Fullstack (App Router + Server Actions) incluye 4 lecciones en total.

¿Qué aprenderé en «UI de carga y errores»?

Implemente estados de carga con `loading.js` y gestione los errores correctamente mediante los boundaries `error.js` de su aplicación. Practicas Next.js 15 Fullstack (App Router + Server Actions) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Next.js 15 Fullstack (App Router + Server Actions)?

No se requiere experiencia previa. Next.js 15 Fullstack (App Router + Server Actions) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.

¿Cuánto tiempo toma la lección «UI de carga y errores»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Next.js 15 Fullstack (App Router + Server Actions)?

Sí. Cada lección de Next.js 15 Fullstack (App Router + Server Actions) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Layouts y componentes de página
  2. Rutas dinámicas y parámetros
  3. UI de carga y errores
  4. Grupos de rutas y layouts anidados
← Volver a Next.js 15 Fullstack (App Router + Server Actions)