Lesson 21 / 25

Loading and Error States

loading.tsx, error.tsx and streaming.

Instant feedback, contained failures

A loading.tsx file in a route segment shows instantly while the segment's Server Components load, using React Suspense under the hood; the rest of the page streams in when ready. You can also wrap slow parts in <Suspense fallback={...}> for finer control. An error.tsx file (a Client Component) acts as an error boundary for its segment, showing fallback UI with a retry option instead of breaking the whole app.

Loading and error files (sketch)

Conventional files for a route segment; not part of the built demo.

// app/products/loading.tsx
export default function Loading() {
  return <p>Loading products...</p>;
}

// app/products/error.tsx
"use client";
export default function Error({ error, reset }: { error: Error; reset: () => void }) {
  return (
    <div>
      <p>Could not load products.</p>
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}

Stream the slow part only

Wrap only slow sections in Suspense so the rest of the page appears immediately.

Quick check: Why must error.tsx be a Client Component?

  • Server Components cannot render text
  • Error boundaries need client-side state and a reset handler
  • It is only used in development
  • It must load CSS
Answer

Error boundaries need client-side state and a reset handler — Interactive recovery happens in the browser.