Error Handling & Loading States

▲ Next.js Lesson 14 Advanced

Next.js includes built-in support for rendering loading skeletons and catching runtime errors gracefully using specialized layout files.

1 error.js reset actions and loading.js skeletons

Managing view transitions and errors is simplified using these reserved files:

  • loading.js: Automatically wraps component routes in a React Suspense boundary, rendering fallback templates instantly while route data fetches.
  • error.js: Wraps routes in a React Error Boundary, catching runtime rendering errors gracefully and providing reset() functions to recover from errors.
2 Implementing a custom error page

Let's check how to write a recovery error view component:

React — error.js template
"use client"; // Error components must be Client Components

import { useEffect } from 'react';

export default function ErrorBoundary({ error, reset }) {
  useEffect(() => {
    // Log error to server analytics
    console.error('Captured runtime error:', error);
  }, [error]);

  return (
    <div class="error-panel">
      <h3>Oops, something went wrong!</h3>
      <button onClick={() => reset()}>Try Again</button>
    </div>
  );
}
3 Code Challenge
Challenge: Write a custom loading.js file that renders a loading spinner layout or card skeleton templates for a dashboard view.