Next.jsQuestion 15 of 15
Task: how do you build filters synced with the URL?
Answer out loud or in your head first, then compare.
Answer
I treat the URL as the source of the applied filters, so refreshing, sharing links and the Back button work. Text that's still being typed can stay local state.
JSX
'use client';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
export default function SortButton() {
const router = useRouter();
const pathname = usePathname();
const current = useSearchParams();
function sortByPrice() {
const params = new URLSearchParams(current.toString());
params.set('sort', 'price');
params.delete('page');
router.replace(`${pathname}?${params.toString()}`, { scroll: false });
}
return <button onClick={sortByPrice}>Sort by price</button>;
}In practice: the server validates the query and filters a large data set; the client can filter a small list already in memory. replace doesn't add a history entry; push does.
To be precise: with static rendering, a component that uses useSearchParams may need a Suspense boundary. The code shows the button; validation and data fetching are the next part of the task.
How did it go? Be honest — “Not yet” puts the question on your review list.