0 day streak
javascript / intermediate
Snippet

Syncing Search State with URL Params

Storing UI state like search queries in the URL makes the page shareable and supports the browser's back button. Using { scroll: false } prevents the page from jumping to the top during navigation updates.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { useRouter, useSearchParams } from 'next/navigation';
export function SearchBar() {
const router = useRouter();
const searchParams = useSearchParams();
const handleSearch = (term: string) => {
const params = new URLSearchParams(searchParams);
if (term) params.set('q', term); else params.delete('q');
router.push(`?${params.toString()}`, { scroll: false });
};
return <input defaultValue={searchParams.get('q') || ''} onChange={(e) => handleSearch(e.target.value)} />;
}
nextjs
Breakdown
1
const params = new URLSearchParams(searchParams);
Creates a mutable copy of the current URL search parameters.
2
router.push(`?${params.toString()}`, { scroll: false });
Updates the URL without a full page reload or scrolling to the top.
3
defaultValue={searchParams.get('q') || ''}
Initializes the input with the value from the URL on load.