Next.js
Beginner
1 min read
Loading UI, Error Boundaries, and Not Found
Example
// app/dashboard/loading.tsx
// Shown automatically while dashboard/page.tsx loads
export default function DashboardLoading() {
return (
<div className="space-y-4 animate-pulse">
<div className="h-8 bg-gray-200 rounded w-1/3" />
<div className="h-32 bg-gray-200 rounded" />
<div className="h-32 bg-gray-200 rounded" />
</div>
);
}
// app/dashboard/error.tsx
'use client';
import { useEffect } from 'react';
export default function DashboardError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error(error);
}, [error]);
return (
<div className="text-center py-16">
<h2 className="text-xl font-semibold">Something went wrong!</h2>
<button
onClick={reset}
className="mt-4 px-4 py-2 bg-blue-600 text-white rounded"
>
Try again
</button>
</div>
);
}
// app/blog/[slug]/page.tsx — trigger 404
import { notFound } from 'next/navigation';
export default async function BlogPost({ params }: { params: { slug: string } }) {
const post = await fetchPost(params.slug);
if (!post) notFound(); // renders app/not-found.tsx
return <article>{post.content}</article>;
}
Related Resources
Next.js Reference
Complete tag & property list
Next.js How-To Guides
Step-by-step practical guides
Next.js Exercises
Practice what you've learned
More in Next.js