Vibe coding with Claude Code course ยท Module 4: Instagram clone
Silence on Deck: a Search with Debounce
In this lesson8
The gallery grows with every voyage and it is harder and harder to find one photo in it. Time for a search by captions. The server will do the searching, because when the photos move to a database, the browser will not get all of them at once. And every question to the server costs: in our case one and a half seconds from lesson 3_4.
The problem: five questions for one word
The captain types "watch". The field changes five times: "w", "wa", "wat", "watc" and so on. If every change sends a question to the server, the server searches five times, four results are useless to anybody, and the skeleton blinks at every letter.
The solution is debouncing: you wait with sending the question until the typist makes a pause. Every new letter cancels the countdown and starts it from zero, so the question goes out only after 300 milliseconds of silence. Like a helmsman who does not turn the wheel at every gust, but waits until the wind settles.
The phrase will also go into the page address, as ?q=watch. That part of the address after the question mark is a search param. Thanks to it you can send the link to the results to the crew, and after a refresh the page remembers what you were looking for.
Request for Claude Code
The request says who searches, where the field stands, how long the silence lasts and what not to do:
Request for Claude Code:
Add a search by photo captions to Treasure Gallery. The phrase goes
into the address as ?q=, and the server filters: getPhotos(query) in
@lib/photos.ts, regardless of letter case. The field stands above the
grid in a new Client Component components/SearchBox.tsx and changes
the address through router.replace only after 300 ms without typing
(debounce). No new packages and no setState in useEffect. An empty
phrase removes q from the address. When nothing matches, say that no
photo has such a caption. Do not add memo, useMemo or useCallback.
At the end run npm run build and npm run lint.The bans have reasons. A new package for debounce is somebody else's code in the project for a few lines. Setting state directly in an effect breaks the react-hooks/set-state-in-effect rule and npm run lint will reject it. Besides, an effect is not needed here: the question is sent because somebody types, and a reaction to an event belongs in an event handler. You will read about memoization at the end of the lesson.
What Claude wrote: the server searches
Open lib/photos.ts in Cursor. The function from lesson 3_4 got a parameter:
export async function getPhotos(query = ""): Promise<Photo[]> {
await new Promise((resolve) => setTimeout(resolve, 1500));
const phrase = query.trim().toLocaleLowerCase("en");
return photos.filter((photo) =>
photo.caption.toLocaleLowerCase("en").includes(phrase),
);
}query = "" is a default value, so a call without a phrase works as before. toLocaleLowerCase("en") turns letters into small ones by English rules and "CHEST" will find "chest". filter keeps the photos whose caption contains the phrase, and an empty phrase matches every caption. The delay stayed: it is our fake cost of every question.
The page app/gallery/page.tsx reads the phrase from the address:
export default async function GalleryPage({ searchParams }: PageProps<"/gallery">) {
const { q } = await searchParams;
const query = typeof q === "string" ? q : "";searchParams are the params from the address, which Next.js gives the page as a promise, which is why await stands before them. PageProps<"/gallery"> is a type that Next.js generates itself for this route, without an import. A param can arrive as text, as a list or not at all, so typeof q === "string" keeps only text and turns the rest into an empty phrase.
Under the header stand the field and the grid:
<SearchBox initialQuery={query} />
<Suspense key={query} fallback={<GallerySkeleton />}>
<PhotoGrid query={query} />
</Suspense>PhotoGrid passes the phrase to getPhotos, and for an empty result with a phrase it says that no photo has such a caption, instead of inviting you to add the first photo. key={query} is new. Every phrase is a new Suspense boundary for React, so with every search the skeleton returns, and Gallery starts anew with fresh photos. Why that matters you will see in the review.
What Claude wrote: the field with debounce
Open components/SearchBox.tsx. The file starts with "use client", because the field reacts to typing. The countdown is kept by useRef from lesson 2_5, and the event handler resets it:
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const handleChange = (value: string) => {
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(() => {
const phrase = value.trim();
router.replace(phrase ? `${pathname}?q=${encodeURIComponent(phrase)}` : pathname);
}, 300);
};Every letter first cancels the previous countdown with clearTimeout, and then sets a new one. Only 300 milliseconds of silence lets the phrase through to router.replace, which changes the address without a new entry in the browser history, so the Back button does not step back one letter at a time. router and pathname (the current path, here /gallery) come from the useRouter and usePathname hooks from next/navigation. encodeURIComponent turns spaces and & characters into a safe form in the address. It is a ref and not a plain let variable because a ref survives the next renders; a plain variable would be rejected by npm run lint with the react-hooks/immutability rule.
Under the function stands the only effect in the file:
useEffect(() => {
return () => {
if (timer.current) clearTimeout(timer.current);
};
}, []);It sets no state, it only cleans up. When somebody types a letter and immediately moves to another page, a countdown without cleanup keeps ticking and after 300 milliseconds pulls them back into the gallery; we checked it. Cleaning up on unmount cancels the countdown together with the component. The field itself has defaultValue={initialQuery}, so it starts with the phrase from the address, and an onChange that calls handleChange.
Captain's review
Run npm run dev, open localhost:3000/gallery and check:
- One question per word. The proof is the terminal with
npm run dev: Next.js prints every request to the page there. Type "watch" at a normal pace and count the new lines. There should be one,GET /gallery?q=watch 200. When Claude skipsclearTimeout, debounce only delays the questions and you will see five:
GET /gallery?q=w 200 in 1529ms (next.js: 1.8ms, application-code: 1527ms)
GET /gallery?q=wa 200 in 1519ms (next.js: 2ms, application-code: 1517ms)
GET /gallery?q=wat 200 in 1520ms (next.js: 8ms, application-code: 1512ms)
GET /gallery?q=watc 200 in 1521ms (next.js: 1.7ms, application-code: 1519ms)
GET /gallery?q=watch 200 in 1517ms (next.js: 1.2ms, application-code: 1516ms)Build and lint pass in both versions, so count the lines and do not believe the assurance "debounce works".
keyonSuspense. This is a typical agent mistake: a boundary without a key. We checked what happens then. While typing, the skeleton does not show, because when the address changes React leaves the old results on the screen, and when the server answers, the grid still has all six photos.Gallerytook the photos into state throughuseState(photos), and the starting value is computed only on the first render. After a page refresh the result is correct, while typing it is not, and that confuses the most. In the diff look forkey={query}.- Letter case and an empty result. Type "CHEST" in capitals: the photo with the caption "We buried the chest here" should be found. Type "kraken": the sentence that no photo has such a caption should appear, not an invitation to add the first photo.
- A link to the results. Copy the address with
?q=into a new tab: the results and the phrase in the field are the same. Clear the field: the address loses?q=.
At the end find the /gallery line in the output of npm run build. It now has ฦ (Dynamic) next to it: the page uses the params of the address, so it is created on every visit, and the skeleton from lesson 3_4 is visible also after the build.
Debounce or useDeferredValue
Debounce saves the server. When you filter photos that the browser already has, the React documentation recommends something else: useDeferredValue. The hook returns a delayed copy of a value, and React draws the list for the new phrase in the background and interrupts that work when the next letter arrives:
const [query, setQuery] = useState("");
const deferredQuery = useDeferredValue(query);
const phrase = deferredQuery.trim().toLocaleLowerCase("en");
const visible = items.filter((photo) =>
photo.caption.toLocaleLowerCase("en").includes(phrase),
);The field shows query right away, and the list uses deferredQuery. There is no fixed number of milliseconds here: on a fast computer the delay is unnoticeable, on a slow one the list lags a little behind the field. The documentation also stresses that useDeferredValue alone does not reduce the number of network requests. Hence a simple rule: you ask the server, use debounce; you draw in the browser, use useDeferredValue. You can combine both techniques.
Memo in reserve
The request forbade three tools that Claude likes to add "for performance". React.memo skips redrawing a component when its props did not change. useMemo remembers the result of a calculation, and useCallback remembers the function itself, so that on the next render it is the same function. Each of them adds code and dependencies to watch, and with six photos none of them speeds anything up. I recommend a rule: first measure, for example in the Profiler tab of React DevTools, then optimize. If Claude adds any of them without a measurement, ask what it measured.
Next step
Before you commit, run /code-review from lesson 2_9 and read the report in Cursor. Then a commit, for example "Gallery: search by captions with debounce", and a small extension:
In @components/PhotoGrid.tsx above the grid show how many photos match
the phrase, with correct English plural forms: 1 photo, 2 photos,
5 photos. Only when the phrase is not empty. Change nothing outside
this file.In the diff check what the pluralizing function returns for 0 and 1: "0 photos" and "1 photo" are right. Many simple if conditions stumble on exactly these numbers.
In the editor below you switch debounce on and off and count the questions to the fake server: type "watch" with and without debounce, and then compare the counter.
Remember: the helmsman waits until the wind settles, and the captain does not believe in "it should work", but counts the lines in the server's logbook.
Code for this lesson: App.jsx
// A search with debounce: how many questions go to the server?
// The server is fake: it waits 600 ms and filters photos by caption.
import { useEffect, useRef, 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',
caption: 'We buried the chest here',
},
{
id: 'fale-z-gory',
src: 'https://images.unsplash.com/photo-1505118380757-91f5f5632de0?w=600',
alt: 'Turquoise waves at a white beach seen from above',
caption: 'The bay from the lookout',
},
{
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',
caption: 'Night watch',
},
{
id: 'palmy',
src: 'https://images.unsplash.com/photo-1519046904884-53103b34b206?w=600',
alt: 'Palm trees and a straw umbrella on a white beach',
caption: 'The island from the map',
},
{
id: 'szlak',
src: 'https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?w=600',
alt: 'A road between red rocks leading toward a mountain',
caption: 'The trail to the hideout',
},
{
id: 'rafa',
src: 'https://images.unsplash.com/photo-1544551763-46a013bb70d5?w=600',
alt: 'A diver among a school of yellow fish at the reef',
caption: 'Diving at the reef',
},
];
function fakeServer(query) {
return new Promise((resolve) => {
setTimeout(() => {
const phrase = query.trim().toLocaleLowerCase('en');
resolve(
photos.filter((photo) =>
photo.caption.toLocaleLowerCase('en').includes(phrase),
),
);
}, 600);
});
}
export default function App() {
const [debounce, setDebounce] = useState(true);
const [requests, setRequests] = useState([]);
const [results, setResults] = useState(photos);
const timer = useRef(null);
const send = async (value) => {
setRequests((prev) => [...prev, value.trim() || '(empty phrase)']);
const found = await fakeServer(value);
setResults(found);
};
const handleChange = (value) => {
if (!debounce) {
send(value);
return;
}
// Every letter cancels the previous countdown and sets a new one
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(() => send(value), 300);
};
// Cleanup: the countdown does not outlive the component
useEffect(() => {
return () => {
if (timer.current) clearTimeout(timer.current);
};
}, []);
return (
<div className="min-h-screen bg-slate-100 p-4 text-slate-900">
<h1 className="mb-3 text-2xl font-bold">Treasure Gallery</h1>
<label className="mb-2 flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={debounce}
onChange={(event) => setDebounce(event.target.checked)}
/>
Debounce 300 ms
</label>
<input
type="search"
onChange={(event) => handleChange(event.target.value)}
placeholder="Search captions..."
aria-label="Search photo captions"
className="mb-3 w-full rounded border border-slate-300 bg-white px-3 py-2"
/>
<div className="mb-3 rounded bg-white p-3 text-sm">
<div className="mb-1 flex items-center justify-between">
<span className="font-semibold">Questions to the server: {requests.length}</span>
<button
type="button"
onClick={() => setRequests([])}
className="rounded bg-slate-200 px-2 py-1 text-xs"
>
Reset counter
</button>
</div>
<ol className="list-decimal pl-5 text-slate-600">
{requests.map((phrase, index) => (
<li key={index}>{phrase}</li>
))}
</ol>
</div>
{results.length === 0 ? (
<p className="py-8 text-center text-slate-600">
No photo has such a caption.
</p>
) : (
<ul className="grid grid-cols-2 gap-1 sm:grid-cols-3">
{results.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"
/>
<span className="absolute inset-x-0 bottom-0 bg-black/60 px-2 py-1 text-xs text-white">
{photo.caption}
</span>
</li>
))}
</ul>
)}
</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 is debouncing in a search field?
2. After typing the word "watch" the terminal with npm run dev shows five lines: GET /gallery?q=w, ?q=wa and so on up to ?q=watch. What is most likely missing in handleChange?
These are 2 of 5 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Order the lines of the handleChange function with debounce (top to bottom):
- Click in order
Click the fragments in order to read the q param from the page address: