loading.tsx and error.tsx
8 min read
Handling Loading and Error States
Next.js has built-in support for loading and error states through special files. loading.tsx is automatically used as a React Suspense fallback while a page or its data is being fetched. error.tsx becomes an error boundary that catches rendering errors in its segment.
tsx
// src/app/blog/loading.tsx
export default function Loading() {
return (
<div className="animate-pulse">
<div className="h-8 bg-gray-200 rounded mb-4" />
<div className="h-4 bg-gray-200 rounded w-2/3" />
</div>
);
}tsx
// src/app/blog/error.tsx
"use client";
export default function Error({
error,
reset,
}: {
error: Error;
reset: () => void;
}) {
return (
<div>
<h2>Something went wrong!</h2>
<p>{error.message}</p>
<button onClick={reset}>Try again</button>
</div>
);
}error.tsx must be a Client Component ("use client"). This is required because it needs to use the reset callback to re-render the segment after an error.
Ready to test yourself?
Practice Next.js— quiz & coding exercises