Vibe coding with Claude Code course · Module 4: Instagram clone
The Ship's Frame: Loading States and a Gallery Skeleton
In this lesson8
So far the gallery photos live in the lib/photos.ts file so the page has them at hand the moment it is built. A real gallery fetches them from a database or another server, and that takes time. In this lesson you will fake a slow server, and Claude Code will build a skeleton of the gallery for the waiting time and add two states that agents like to forget: the error and the empty chest.
The problem: a dead link and an empty screen
A page that waits for data has nothing to show. Refreshed in the browser, it stands without a response for a long time, and after a click on a link from another page it looks as if the click did not work. The Next.js documentation warns that the user then feels the app is not responding. The crew clicks a second time, refreshes, and starts waiting from scratch.
The cure is a loading state, a separate look of the page for the waiting time. Best of all one that has the shape of the future content. A gray outline of tiles in the place of photos is called a skeleton: you can see what will appear and where, so nothing jumps when the data finally arrives. It is like the outline of a ship in the shipyard: the mast is not there yet, but you know where it will stand.
Request for Claude Code: a slow server and loading.tsx
The first step touches four files, but each one is simple, so it can do without a plan. The request says where the delay should appear, what not to use and what shape the skeleton should have:
Request for Claude Code:
In @lib/photos.ts add an async function getPhotos() that waits 1.5 s
and returns the photos. It is a fake slow server for learning, explain
that in a comment. The page @app/gallery/page.tsx must wait for
getPhotos() on the server, without "use client" and without useEffect.
For the waiting time add app/gallery/loading.tsx: a gray circle in the
place of the avatar, a bar in the place of the title and a grid of gray
animate-pulse tiles in a separate file components/GallerySkeleton.tsx,
with the same columns and gap as the grid in @components/Gallery.tsx.
At the end run npm run build and npm run lint.The ban on useEffect has a reason. In lesson 2_3 the effect ran in the browser, but a page in the App Router is a Server Component by default and can wait for data on the server itself before it sends the HTML. Older tutorials fetch data in an effect of a client component, and Claude sometimes goes that way out of habit. The page then waits for nothing, so the skeleton from loading.tsx never shows at all.
What Claude wrote: the fake server
Open lib/photos.ts in Cursor. Under the photo array there is a new function:
// For learning we fake a slow server: 1.5 s of waiting.
// When the photos move to a database, only the query will stay.
export async function getPhotos(): Promise<Photo[]> {
await new Promise((resolve) => setTimeout(resolve, 1500));
return photos;
}async before a function means it returns a promise (Promise), a result that will arrive later. await tells it to wait for that promise, and new Promise with setTimeout is simply a pause of 1500 milliseconds. The photos array did not change, you just have to wait for it, like for the answer of a real server.
In app/gallery/page.tsx the beginning of the component changed:
export default async function GalleryPage() {
const photos = await getPhotos();The page component became an async function and waits for the photos before it returns anything. Only a Server Component can do that: there is no "use client", no state and no effects here. The header and the grid below stayed as in lesson 3_3.
What Claude wrote: the skeleton and loading.tsx
Open components/GallerySkeleton.tsx. It is a list of gray tiles in the same grid as the photos:
export default function GallerySkeleton() {
return (
<div role="status">
<span className="sr-only">Loading photos from the voyage…</span>
<ul
aria-hidden="true"
className="grid grid-cols-1 gap-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4"
>
{Array.from({ length: 8 }, (_, index) => (
<li key={index} className="aspect-square animate-pulse bg-gray-200" />
))}
</ul>
</div>
);
}Array.from({ length: 8 }, ...) creates eight tiles, and the grid classes are the same as in Gallery.tsx, so the skeleton has as many columns as the gallery on every screen. aspect-square makes squares, bg-gray-200 gives the gray color, and animate-pulse keeps dimming the tile and brightening it again. A key from the index is fine here, although in lesson 2_8 you avoided it: a list of gray tiles never changes or reorders.
Gray tiles tell nothing to a person whose screen reader reads the page aloud, so aria-hidden="true" hides them from it. Instead the reader reads the sentence with the sr-only class, invisible on the screen, and role="status" tells it to announce it.
The skeleton of the whole page lives in app/gallery/loading.tsx:
import GallerySkeleton from "@/components/GallerySkeleton";
export default function Loading() {
return (
<main className="mx-auto max-w-4xl p-4">
<div className="mb-6 flex items-center gap-4">
<div className="h-24 w-24 animate-pulse rounded-full bg-gray-200" />
<div className="h-8 w-48 animate-pulse rounded bg-gray-200" />
</div>
<GallerySkeleton />
</main>
);
}loading.tsx is a special Next.js file, like page.tsx. Nobody imports it: Next.js itself wraps the page from the same folder in it and shows it while the page waits. According to the documentation it does so through <Suspense>, a React component you will come back to in a moment. Refresh localhost:3000/gallery: for one and a half seconds a gray circle, a bar and tiles pulse, and then the gallery appears.
Four states and Suspense closer to the data
When you look at the skeleton, you will see a waste: you know the avatar and the title from the start, and they wait too. loading.tsx covers the whole page at once. A narrower curtain is given by <Suspense> itself: you wrap only the part that waits for data, and in the fallback prop you say what to show instead. The Next.js documentation recommends exactly <Suspense> close to the place that waits for data.
This is also a good moment for the rest of the states. Every view with data has four of them: loading, error, empty and success. Asked for "a list of photos", Claude will probably do the first and the last and skip the middle ones, because nobody asked for them. That is why the request names all four:
Request for Claude Code:
/plan The profile header does not need the photos, so let it stand
right away. Move the waiting for getPhotos() into a new Server
Component components/PhotoGrid.tsx and wrap it in @app/gallery/page.tsx
in Suspense with GallerySkeleton. Handle four states: loading (the
skeleton), an empty list (an invitation to add the first photo), an
error (app/gallery/error.tsx with a Try again button, following the
Next.js docs from node_modules/next/dist/docs) and success.
@components/Gallery.tsx stays unchanged. End every step with
npm run build and npm run lint.The pointer to the documentation in node_modules has a reason. The AGENTS.md file from the generator warns Claude that this version of Next.js has changes it does not know from its training data, and the error file changed recently. In the plan look for the four files from the request. If Claude starts turning Gallery.tsx into a Server Component, press Esc: the likes from lesson 3_3 need state, and state lives only in a client component.
What Claude wrote: Suspense, empty and error
Open app/gallery/page.tsx. The page no longer waits for anything, and under the header there is:
<Suspense fallback={<GallerySkeleton />}>
<PhotoGrid />
</Suspense>The server sends the header and the skeleton from fallback right away, and when PhotoGrid finishes waiting, it sends the ready grid into the same place. Sending a page in pieces like this is called streaming. loading.tsx can stay: it will cover the whole page if it ever has to wait as a whole again.
The waiting moved to components/PhotoGrid.tsx:
export default async function PhotoGrid() {
const photos = await getPhotos();
if (photos.length === 0) {
return (
<p className="py-12 text-center text-gray-600">
The chest is still empty. Add the first photo from the voyage.
</p>
);
}
return <Gallery photos={photos} />;
}It is an async server component, like the page in the first step. It checks the empty state only after await, so it never confuses it with loading. When the photos are there, it hands them to the Gallery component, and the likes and the window work as in lesson 3_3.
The last state lives in app/gallery/error.tsx:
"use client";
export default function GalleryError({
retry,
}: {
error: unknown;
retry: () => void;
}) {
return (
<main className="mx-auto max-w-4xl p-4 text-center">
<h2 className="text-xl font-bold">A storm held back the photos</h2>
<p className="my-2 text-gray-600">Could not load the gallery.</p>
<button
type="button"
onClick={() => retry()}
className="rounded bg-gray-900 px-4 py-2 text-white"
>
Try again
</button>
</main>
);
}When something in the /gallery route throws an error, Next.js shows this component instead of the page, together with the header, because error.tsx covers the whole route folder. According to the documentation the error file must be a client component, hence "use client". retry() fetches the data and draws the page again: if the storm has passed, the gallery returns to its place.
Captain's review
Run npm run dev and check:
- The skeleton has the shape of the gallery. Refresh the page and narrow the window during loading: the gray tiles arrange into four, three, two and one column, just like the photos later. When the skeleton has different grid classes than
Gallery.tsx, the page will jump the moment the data arrives. - The error really shows. Ask Claude for a temporary
throw new Error("Storm")at the start ofgetPhotos, refresh the page and look at the message. In development mode Next.js adds an error badge in the corner; it is a hint for you, the crew will not see it. Then undo the change with/rewind. retry, notreset. This is a typical agent mistake. Older versions of Next.js gave the error file only aresetfunction, and Claude often writes it from memory:
export default function GalleryError({
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {TypeScript and lint pass, the message shows, the button looks like it works. The documentation says, however, that reset only clears the error and draws the page again, without fetching the data again. We checked it: after the storm had passed, the button with reset still showed the message, and the one with retry brought the gallery back. In the diff look for the word retry.
- The skeleton only in development mode. Run
npm run buildand find the/galleryline in the output. It has a circle○next to it, which the legend describes as "prerendered as static content": the page was created once, at build time, and the one and a half seconds of waiting passed then, on your computer. Afternpm run startyou will not see the skeleton, and new photos from the database would appear only after the next build. Innpm run devthe page is created on every visit, which is why the skeleton is visible there. The search from the next lesson will change that.
Next step
When the review passes, ask for a commit, for example "Gallery: skeleton, empty state and error page". Then a small extension of the error page:
In @app/gallery/error.tsx log the error to the browser console through
useEffect with console.error, like in the example from the Next.js
documentation. Change nothing outside this file.You will check it with another temporary storm: an entry with the message will appear in the browser console. In the production version, however, it will only be a generic message with the digest identifier. The documentation explains that Next.js hides the details of server errors so as not to reveal anything sensitive; you will find the full text in the server logs under that identifier.
In the editor below you switch between the four states of the gallery and replay the one and a half seconds of loading. See that the skeleton and the photos take the same place, and then solve the tasks.
Remember: a skeleton is the outline of a ship in the shipyard, and the captain orders all four states from Claude Code, because the crew will see every one of them.
Code for this lesson: App.jsx
// Four states of the gallery: loading, error, empty and success
// In the project the states come from loading.tsx, Suspense, error.tsx and PhotoGrid.
// Here you switch them with buttons to compare what the crew sees.
import { useState } from 'react';
const photos = [
{
id: 'zachod-na-plazy',
src: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=600',
alt: 'Waves on a sandy beach at sunset',
},
{
id: 'fale-z-gory',
src: 'https://images.unsplash.com/photo-1505118380757-91f5f5632de0?w=600',
alt: 'Turquoise waves at a white beach seen from above',
},
{
id: 'zaglowka-noca',
src: 'https://images.unsplash.com/photo-1534447677768-be436bb09401?w=600',
alt: 'A small sailboat on a calm sea under a starry sky',
},
{
id: 'palmy',
src: 'https://images.unsplash.com/photo-1519046904884-53103b34b206?w=600',
alt: 'Palm trees and a straw umbrella on a white beach',
},
{
id: 'szlak',
src: 'https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?w=600',
alt: 'A road between red rocks leading toward a mountain',
},
{
id: 'rafa',
src: 'https://images.unsplash.com/photo-1544551763-46a013bb70d5?w=600',
alt: 'A diver among a school of yellow fish at the reef',
},
];
// The same grid in the skeleton and in the gallery: nothing jumps
const gridClasses = 'grid grid-cols-2 gap-1 sm:grid-cols-3';
function GallerySkeleton() {
return (
<div role="status">
<span className="sr-only">Loading photos from the voyage…</span>
<ul aria-hidden="true" className={gridClasses}>
{Array.from({ length: 6 }, (_, index) => (
<li key={index} className="aspect-square animate-pulse bg-gray-200" />
))}
</ul>
</div>
);
}
function PhotoGrid({ items }) {
return (
<ul className={gridClasses}>
{items.map((photo) => (
<li key={photo.id} className="relative aspect-square bg-slate-800">
<img
src={photo.src}
alt={photo.alt}
className="absolute inset-0 h-full w-full object-cover"
/>
</li>
))}
</ul>
);
}
const views = [
['loading', 'Loading'],
['error', 'Error'],
['empty', 'Empty'],
['success', 'Success'],
];
export default function App() {
const [view, setView] = useState('success');
// We fake a slow server: a second and a half of skeleton, then the photos
const replay = () => {
setView('loading');
setTimeout(() => setView('success'), 1500);
};
return (
<div className="min-h-screen bg-slate-100 p-4 text-slate-900">
<h1 className="mb-1 text-2xl font-bold">Treasure Gallery</h1>
<p className="mb-3 text-sm text-slate-600">Photos from the voyage</p>
<div className="mb-4 flex flex-wrap gap-2">
{views.map(([id, label]) => (
<button
key={id}
type="button"
onClick={() => setView(id)}
aria-pressed={view === id}
className={view === id
? 'rounded bg-slate-900 px-3 py-1 text-sm text-white'
: 'rounded bg-white px-3 py-1 text-sm'}
>
{label}
</button>
))}
<button
type="button"
onClick={replay}
className="rounded bg-amber-500 px-3 py-1 text-sm font-semibold text-slate-900"
>
Replay 1.5 s loading
</button>
</div>
{view === 'loading' && <GallerySkeleton />}
{view === 'error' && (
<div className="py-8 text-center">
<h2 className="text-xl font-bold">A storm held back the photos</h2>
<p className="my-2 text-slate-600">Could not load the gallery.</p>
<button
type="button"
onClick={replay}
className="rounded bg-slate-900 px-4 py-2 text-white"
>
Try again
</button>
</div>
)}
{view === 'empty' && (
<p className="py-12 text-center text-slate-600">
The chest is still empty. Add the first photo from the voyage.
</p>
)}
{view === 'success' && <PhotoGrid items={photos} />}
</div>
);
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the animate-pulse class do on the gray tiles of the gallery skeleton?
2. The Try again button in error.tsx only clears the error and redraws the page, without fetching the photos again. What will you see after clicking it when the storm has already passed?
These are 2 of 5 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Order what happens after entering /gallery when the grid waits inside Suspense:
- Click in order
Click the fragments in order so that the page waits for the photos on the server:
Tasks after this lesson
- QuestionQuiz: animate-pulse in the skeleton
- Put in orderSorting: Loading the gallery step by step
- QuestionQuiz: A button that does not fetch data
- QuestionQuiz: The empty state of the gallery
- Click in orderClick: The page waits for the photos
- QuestionQuiz: loading.tsx and Suspense
- QuestionQuiz: The skeleton after the build