Next.js Loading UI — loading.tsx & Suspense
loading.tsx, same folder లో unна page.tsx data fetch చేస్తున్నప్పుడు, automatic గా fallback UI గా చూపబడుతుంది — ఏ manual state management అవసరం లేదు:
export default function Loading() {
return <p>Loading courses...</p>;
}
Behind the scenes, Next.js ఈ file ni automatic గా <Suspense fallback={"{"}<Loading />{"}"}> లో page.tsx ని wrap చేస్తుంది.
Plain "Loading..." text బదులు, actual content shape ni mimic చేసే skeleton UI vాడితే, perceived performance chాలా better గా అనిపిస్తుంది:
export default function Loading() {
return (
<div className="animate-pulse space-y-4">
<div className="h-6 bg-gray-200 rounded w-1/3"></div>
<div className="h-4 bg-gray-200 rounded w-full"></div>
<div className="h-4 bg-gray-200 rounded w-2/3"></div>
</div>
);
}
Whole route కాకుండా, page లో ఒక్క specific section matrame slow గా load అయితే, దాన్ని <Suspense> తో wrap చేసి, migతా page వెంటనే కనిపించేలా చేయవచ్చు — దీన్నే streaming అంటారు:
import { Suspense } from "react";
import SlowStats from "./SlowStats";
export default function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<Suspense fallback={<p>Loading stats...</p>}>
<SlowStats />
</Suspense>
</div>
);
}
<h1>Dashboard</h1> వెంటనే కనిపిస్తుంది, SlowStats ready అయ్యేవరకు దాని fallback matrame కనిపిస్తుంది — whole page block అవ్వదు.
Page లో fast content ni కూడా slow content తో paatu block చేసి, ఒక్క big spinner చూపించడం — ఇది bad UX. Suspense boundaries ఎక్కడ అవసరమో అక్కడ matrame pెట్టి, fast content వెంటనే render అయ్యేలా చేయాలి.
Create a loading.tsx for a 'reports' route that shows a simple centered spinner message.
export default function Loading() {
return (
<div style={{ textAlign: "center", padding: "40px" }}>
<p>⏳ Generating your report...</p>
</div>
);
}
Q loading.tsx compulsory ah ప్రతి route కి?
Ledు, optional. లేకపోతే, page fully ready అయ్యే వరకు browser default navigation indicator (top progress bar) matrame కనిపిస్తుంది.
Q Suspense, loading.tsx రెండూ ఒకేసారి వాడొచ్చా?
Avunు. loading.tsx మొత్తం route కి apply అవుతుంది; దాని లోపల specific slow components కి extra Suspense boundaries pెట్టి, more granular streaming చేయవచ్చు.
Q Client Component లో Suspense వాడొచ్చా?
Avunు, kani Suspense ప్రధానంగా async Server Components, and lazy-loaded client components (React.lazy) కోసం design చేయబడింది — plain useState loading కోసం కాదు.