Implement a search page in Next.js App Router where search results are server components streamed to the client. Use a client component for the search input that updates URL query params, wrap results in Suspense, and use useTransition to keep old results visible while new ones fetch.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The plan is to build a search page with a client-side input updating URL params inside a startTransition to keep old results visible during fetches, and a server component rendering streamed results wrapped in Suspense with fallback. The provided code covers page.tsx, SearchBox client component, and Results server component fetching data with caching disabled and simulating latency, fitting Next.js App Router conventions.
Below is a minimal example for app/search that satisfies all the requirements:
Server component page that streams search results.
Client component for the search box that updates URL query params.
Suspense around the results.
useTransition in the client component so old results stay visible while new ones fetch.
'use client';
import { useRouter, useSearchParams } from 'next/navigation';
import { useTransition, useEffect, useState } from 'react';
type Props = { initialQuery: string };
export default function SearchInput({ initialQuery }: Props) {
const router = useRouter();
const searchParams = useSearchParams();
const [pending, startTransition] = useTransition();
const [value, setValue] = useState(initialQuery);
// Keep local state in sync when URL changes externally
useEffect(() => setValue(initialQuery), [initialQuery]);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const next = e.target.value;
setValue(next);
startTransition(() => {
const params = new URLSearchParams(searchParams.toString());
if (next) params.set('q', next);
else params.delete('q');
// Keep the scroll position, only update query string
router.replace(`?${params.toString()}`, { scroll: false });
});
};
return (
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
<input
type="text"
value={value}
onChange={handleChange}
placeholder="Type to search…"
style={{ padding: '0.5rem', minWidth: '220px' }}
/>
{pending && <span>Updating…</span>}
</div>
);
}
app/search/SearchResults.tsx (Server Component)
tsx
// This component runs on the server and is streamed to the client.
// Fetch can be dynamic; here we use "no-store" for per-request freshness.
type Product = { id: number; title: string; description: string };
async function fetchProducts(query: string): Promise<Product[]> {
if (!query) return [];
const res = await fetch(
`https://dummyjson.com/products/search?q=${encodeURIComponent(query)}`,
{ cache: 'no-store' }
);
// Artificial delay to make streaming & Suspense noticeable
await new Promise((r) => setTimeout(r, 600));
if (!res.ok) {
throw new Error('Failed to fetch');
}
const data = await res.json();
return data?.products ?? [];
}
export default async function SearchResults({ query }: { query: string }) {
if (!query) {
return <div className="p-4">Start typing to search.</div>;
}
const products = await fetchProducts(query);
if (!products.length) {
return <div className="p-4">No results found.</div>;
}
return (
<ul style={{ marginTop: '1rem', listStyle: 'disc', paddingLeft: '1.5rem' }}>
{products.map((p) => (
<li key={p.id}>
<div>{p.title}</div>
<small style={{ color: '#666' }}>{p.description}</small>
</li>
))}
</ul>
);
}
How it works
Search input is a client component; it uses useTransition to call router.replace when the user types. Marking the route change as a transition keeps the previous results visible while new data streams in.
URL query (?q=...) drives the server component SearchResults (which fetches data). Because it’s a server component wrapped in Suspense, it streams in once the fetch resolves.
Suspense fallback renders a loading state only when there’s no previous UI (or during the initial request). During transitions, the old results stay until new ones arrive.