Topic 15 of 39
Loading UI
Overview
The loading.tsx file allows you to create fallback UI (like skeletons or spinners) that Next.js automatically displays while the content of a route segment is loading. It works out-of-the-box using React Suspense.
Syntax
tsx
// app/dashboard/loading.tsx
export default function Loading() {
// You can add any UI inside Loading, including a Skeleton.
return (
<div className="flex h-screen items-center justify-center">
<div className="spinner border-4 border-blue-500 rounded-full w-12 h-12 animate-spin"></div>
</div>
);
}Common Pitfalls
- Assuming
loading.tsxcovers client-side data fetching. It primarily catches async Server Components that are awaited. - Placing heavy logic in the loading component—it should be instantaneous and lightweight.
Interview Questions
Q:
Under the hood, how does Next.js implement the
loading.tsx file?A:
Next.js automatically wraps the route segment's page.tsx and its nested children in a React <Suspense> boundary, using the loading.tsx component as the fallback prop.
Real-World Example
Using a skeleton loader to improve perceived performance while database queries run.
example
tsx
// app/posts/loading.tsx
export default function PostsLoading() {
return (
<div className="space-y-4">
<div className="h-10 bg-gray-200 rounded animate-pulse"></div>
<div className="h-10 bg-gray-200 rounded animate-pulse"></div>
<div className="h-10 bg-gray-200 rounded animate-pulse"></div>
</div>
);
}Check Your Knowledge
Test your understanding of Loading UI with these quick questions.